<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha256-CTSx/A06dm1B063156EVh15m6Y67pAjZZaQc89LLSrU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.24/fancybox/fancybox.css" integrity="sha256-vQkngPS8jiHHH0I6ABTZroZk8NPZ7b+MUReOFE9UsXQ=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"rjyblog.gitee.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.18.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":null},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文基于Android 8.0源码分析。以mediaserver为例剖析binder addService的流程。">
<meta property="og:type" content="article">
<meta property="og:title" content="Android binder剖析之addService">
<meta property="og:url" content="https://rjyblog.gitee.io/posts/27252.html">
<meta property="og:site_name" content="任建勇的博客">
<meta property="og:description" content="本文基于Android 8.0源码分析。以mediaserver为例剖析binder addService的流程。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-11-23T03:16:04.000Z">
<meta property="article:modified_time" content="2023-08-17T01:46:48.258Z">
<meta property="article:author" content="Jason">
<meta property="article:tag" content="Android">
<meta property="article:tag" content="binder">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://rjyblog.gitee.io/posts/27252.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://rjyblog.gitee.io/posts/27252.html","path":"posts/27252.html","title":"Android binder剖析之addService"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Android binder剖析之addService | 任建勇的博客</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">任建勇的博客</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-ProcessState%E6%89%93%E5%BC%80binder%E8%AE%BE%E5%A4%87"><span class="nav-text">1. ProcessState打开binder设备</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%8E%B7%E5%8F%96-IServiceManager"><span class="nav-text">2. 获取 IServiceManager</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#DECLARE-META-INTERFACE%E5%AE%8F"><span class="nav-text">DECLARE_META_INTERFACE宏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IMPLEMENT-META-INTERFACE%E5%AE%8F"><span class="nav-text">IMPLEMENT_META_INTERFACE宏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96IServiceManager%E5%B0%8F%E7%BB%93"><span class="nav-text">获取IServiceManager小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-addService%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90"><span class="nav-text">3. addService流程分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#BpServiceManager%E7%B1%BB"><span class="nav-text">BpServiceManager类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MediaPlayerService%E7%B1%BB"><span class="nav-text">MediaPlayerService类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BpServiceManager-addService"><span class="nav-text">BpServiceManager::addService</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IPCThreadState-transact"><span class="nav-text">IPCThreadState::transact()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Parcel%E7%AD%89%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%88%86%E6%9E%90"><span class="nav-text">Parcel等数据结构分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IPCThreadState-waitForResponse"><span class="nav-text">IPCThreadState::waitForResponse</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IPCThreadState-talkWithDriver"><span class="nav-text">IPCThreadState::talkWithDriver</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-ServiceManager%E5%88%86%E6%9E%90"><span class="nav-text">4. ServiceManager分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%A5%E5%8F%A3%E5%87%BD%E6%95%B0-main"><span class="nav-text">入口函数 main</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ServiceManager%E6%89%93%E5%BC%80binder%E8%AE%BE%E5%A4%87"><span class="nav-text">ServiceManager打开binder设备</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%88%90%E4%B8%BAcontext-manager"><span class="nav-text">成为context_manager</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#binder-loop%E5%BE%AA%E7%8E%AF"><span class="nav-text">binder_loop循环</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jason"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">Jason</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">66</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://rjyblog.gitee.io/posts/27252.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="Jason">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="任建勇的博客">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Android binder剖析之addService | 任建勇的博客">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Android binder剖析之addService
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-23 11:16:04" itemprop="dateCreated datePublished" datetime="2020-11-23T11:16:04+08:00">2020-11-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-08-17 09:46:48" itemprop="dateModified" datetime="2023-08-17T09:46:48+08:00">2023-08-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文基于Android 8.0源码分析。以mediaserver为例剖析binder addService的流程。</p>
<span id="more"></span>

<p>先来看下addService的时序图：</p>
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="678px" preserveAspectRatio="none" style="width:989px;height:678px;background:#FFFFFF;" version="1.1" viewBox="0 0 989 678" width="989px" zoomAndPan="magnify"><defs/><g><rect fill="#FFFFFF" height="181.3984" style="stroke:#181818;stroke-width:1.0;" width="10" x="209.5" y="67.4297"/><rect fill="#FFFFFF" height="123.2656" style="stroke:#181818;stroke-width:1.0;" width="10" x="214.5" y="104.5625"/><rect fill="#FFFFFF" height="54.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="219.5" y="146.6953"/><rect fill="#FFFFFF" height="101.2656" style="stroke:#181818;stroke-width:1.0;" width="10" x="358.5" y="277.9609"/><rect fill="#FFFFFF" height="89.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="547.5" y="349.2266"/><rect fill="#FFFFFF" height="89.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="672" y="408.3594"/><rect fill="#FFFFFF" height="194.5313" style="stroke:#181818;stroke-width:1.0;" width="10" x="786" y="467.4922"/><rect fill="#FFFFFF" height="85.2656" style="stroke:#181818;stroke-width:1.0;" width="10" x="791" y="576.7578"/><rect fill="#FFFFFF" height="43.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="796" y="618.8906"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="77" x2="77" y1="36.2969" y2="671.0234"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="214" x2="214" y1="36.2969" y2="671.0234"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="363" x2="363" y1="36.2969" y2="671.0234"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="552.5" x2="552.5" y1="36.2969" y2="671.0234"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="676.5" x2="676.5" y1="36.2969" y2="671.0234"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="790.5" x2="790.5" y1="36.2969" y2="671.0234"/><line style="stroke:#181818;stroke-width:0.5;stroke-dasharray:5.0,5.0;" x1="952.5" x2="952.5" y1="36.2969" y2="671.0234"/><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="145" x="5" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="131" x="12" y="24.9951">main_mediaserver</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="109" x="160" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="95" x="167" y="24.9951">ProcessState</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="153" x="287" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="139" x="294" y="24.9951">MediaPlayerService</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="148" x="478.5" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="134" x="485.5" y="24.9951">BpServiceManager</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="81" x="636.5" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="67" x="643.5" y="24.9951">BpBinder</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="127" x="727.5" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="113" x="734.5" y="24.9951">IPCThreadState</text><rect fill="#E2E2F0" height="30.2969" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="61" x="922.5" y="5"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="47" x="929.5" y="24.9951">binder</text><rect fill="#FFFFFF" height="181.3984" style="stroke:#181818;stroke-width:1.0;" width="10" x="209.5" y="67.4297"/><rect fill="#FFFFFF" height="123.2656" style="stroke:#181818;stroke-width:1.0;" width="10" x="214.5" y="104.5625"/><rect fill="#FFFFFF" height="54.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="219.5" y="146.6953"/><rect fill="#FFFFFF" height="101.2656" style="stroke:#181818;stroke-width:1.0;" width="10" x="358.5" y="277.9609"/><rect fill="#FFFFFF" height="89.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="547.5" y="349.2266"/><rect fill="#FFFFFF" height="89.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="672" y="408.3594"/><rect fill="#FFFFFF" height="194.5313" style="stroke:#181818;stroke-width:1.0;" width="10" x="786" y="467.4922"/><rect fill="#FFFFFF" height="85.2656" style="stroke:#181818;stroke-width:1.0;" width="10" x="791" y="576.7578"/><rect fill="#FFFFFF" height="43.1328" style="stroke:#181818;stroke-width:1.0;" width="10" x="796" y="618.8906"/><polygon fill="#181818" points="197.5,63.4297,207.5,67.4297,197.5,71.4297,201.5,67.4297" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="77.5" x2="203.5" y1="67.4297" y2="67.4297"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="33" x="84.5" y="62.3638">self()</text><line style="stroke:#181818;stroke-width:1.0;" x1="219.5" x2="266.5" y1="91.5625" y2="91.5625"/><line style="stroke:#181818;stroke-width:1.0;" x1="266.5" x2="266.5" y1="91.5625" y2="104.5625"/><line style="stroke:#181818;stroke-width:1.0;" x1="225.5" x2="266.5" y1="104.5625" y2="104.5625"/><polygon fill="#181818" points="235.5,100.5625,225.5,104.5625,235.5,108.5625,231.5,104.5625" style="stroke:#181818;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="125" x="231.5" y="86.4966">new ProcessState()</text><line style="stroke:#181818;stroke-width:1.0;" x1="224.5" x2="271.5" y1="133.6953" y2="133.6953"/><line style="stroke:#181818;stroke-width:1.0;" x1="271.5" x2="271.5" y1="133.6953" y2="146.6953"/><line style="stroke:#181818;stroke-width:1.0;" x1="230.5" x2="271.5" y1="146.6953" y2="146.6953"/><polygon fill="#181818" points="240.5,142.6953,230.5,146.6953,240.5,150.6953,236.5,146.6953" style="stroke:#181818;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="76" x="236.5" y="128.6294">open_driver</text><polygon fill="#181818" points="941,176.8281,951,180.8281,941,184.8281,945,180.8281" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="229.5" x2="947" y1="180.8281" y2="180.8281"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="32" x="236.5" y="175.7622">open</text><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="229.5" x2="271.5" y1="199.8281" y2="199.8281"/><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="271.5" x2="271.5" y1="199.8281" y2="212.8281"/><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="224.5" x2="271.5" y1="212.8281" y2="212.8281"/><polygon fill="#181818" points="234.5,208.8281,224.5,212.8281,234.5,216.8281,230.5,212.8281" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="224.5" x2="266.5" y1="226.8281" y2="226.8281"/><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="266.5" x2="266.5" y1="226.8281" y2="239.8281"/><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="219.5" x2="266.5" y1="239.8281" y2="239.8281"/><polygon fill="#181818" points="229.5,235.8281,219.5,239.8281,229.5,243.8281,225.5,239.8281" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="#181818" points="88.5,244.8281,78.5,248.8281,88.5,252.8281,84.5,248.8281" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" x1="82.5" x2="213.5" y1="248.8281" y2="248.8281"/><polygon fill="#181818" points="346.5,273.9609,356.5,277.9609,346.5,281.9609,350.5,277.9609" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="77.5" x2="352.5" y1="277.9609" y2="277.9609"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="68" x="84.5" y="272.895">instantiate</text><line style="stroke:#181818;stroke-width:1.0;" x1="368.5" x2="410.5" y1="307.0938" y2="307.0938"/><line style="stroke:#181818;stroke-width:1.0;" x1="410.5" x2="410.5" y1="307.0938" y2="320.0938"/><line style="stroke:#181818;stroke-width:1.0;" x1="369.5" x2="410.5" y1="320.0938" y2="320.0938"/><polygon fill="#181818" points="379.5,316.0938,369.5,320.0938,379.5,324.0938,375.5,320.0938" style="stroke:#181818;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="165" x="375.5" y="302.0278">new MediaPlayerService()</text><polygon fill="#181818" points="535.5,345.2266,545.5,349.2266,535.5,353.2266,539.5,349.2266" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="368.5" x2="541.5" y1="349.2266" y2="349.2266"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="71" x="375.5" y="344.1606">addService</text><polygon fill="#181818" points="660,404.3594,670,408.3594,660,412.3594,664,408.3594" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="557.5" x2="666" y1="408.3594" y2="408.3594"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="53" x="564.5" y="403.2935">transact</text><polygon fill="#181818" points="774,463.4922,784,467.4922,774,471.4922,778,467.4922" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="682" x2="780" y1="467.4922" y2="467.4922"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="53" x="689" y="462.4263">transact</text><line style="stroke:#181818;stroke-width:1.0;" x1="796" x2="838" y1="526.625" y2="526.625"/><line style="stroke:#181818;stroke-width:1.0;" x1="838" x2="838" y1="526.625" y2="539.625"/><line style="stroke:#181818;stroke-width:1.0;" x1="797" x2="838" y1="539.625" y2="539.625"/><polygon fill="#181818" points="807,535.625,797,539.625,807,543.625,803,539.625" style="stroke:#181818;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="138" x="803" y="521.5591">writeTransactionData</text><line style="stroke:#181818;stroke-width:1.0;" x1="796" x2="843" y1="563.7578" y2="563.7578"/><line style="stroke:#181818;stroke-width:1.0;" x1="843" x2="843" y1="563.7578" y2="576.7578"/><line style="stroke:#181818;stroke-width:1.0;" x1="802" x2="843" y1="576.7578" y2="576.7578"/><polygon fill="#181818" points="812,572.7578,802,576.7578,812,580.7578,808,576.7578" style="stroke:#181818;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="110" x="808" y="558.6919">waitForResponse</text><line style="stroke:#181818;stroke-width:1.0;" x1="801" x2="848" y1="605.8906" y2="605.8906"/><line style="stroke:#181818;stroke-width:1.0;" x1="848" x2="848" y1="605.8906" y2="618.8906"/><line style="stroke:#181818;stroke-width:1.0;" x1="807" x2="848" y1="618.8906" y2="618.8906"/><polygon fill="#181818" points="817,614.8906,807,618.8906,817,622.8906,813,618.8906" style="stroke:#181818;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="91" x="813" y="600.8247">talkWithDriver</text><polygon fill="#181818" points="941,649.0234,951,653.0234,941,657.0234,945,653.0234" style="stroke:#181818;stroke-width:1.0;"/><line style="stroke:#181818;stroke-width:1.0;" x1="806" x2="947" y1="653.0234" y2="653.0234"/><text fill="#000000" font-family="sans-serif" font-size="13" lengthAdjust="spacing" textLength="26" x="813" y="647.9575">ioctl</text><!--SRC=[ZPAzJiCm481tFuKtG1LIMJCmb0g9eL94Ap5Mr_XAJgHsT3uQU0f61jw3WO6tAS-1ywFInf7A4ilsVT_zn6SQZ9aZRod3d_VFtTVRxkDRvMHGhvsJbNjH9R1GHYLOqIko1baxhhzNux7Q0Ddb1Ws13v9mU7cjKtOPUZyN4DIZaKwqns9zVg6EBkB0H5kiZWvFCq7kIhHBmnIoHz5TlMsGOfHdxY-3BSpgRLh0At8tdAO-ibx262ZOrK38CDYs5L-4veOTaxBRpC32OoYeJlttcvH1o8IsTOknG4LqOvoqWsW69WpM1yMXg4-fFHBmk_HcaJE2EPZwiAHbL0-85Ockc0GNdOISdOB0QQv9NG79hUDxzAMp7lz92HHF3oJvj7qfCRH_A-GoANu1]--></g></svg>

<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\av\media\mediaserver\main_mediaserver.cpp</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">int</span> argc __unused, <span class="type">char</span> **argv __unused)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">signal</span>(SIGPIPE, SIG_IGN);</span><br><span class="line"></span><br><span class="line">    <span class="function">sp&lt;ProcessState&gt; <span class="title">proc</span><span class="params">(ProcessState::self())</span></span>;  <span class="comment">// 1. ProcessState是个单例，每个进程只有一个实例，binder设备的打开操作就是在此</span></span><br><span class="line">    <span class="function">sp&lt;IServiceManager&gt; <span class="title">sm</span><span class="params">(defaultServiceManager())</span></span>;  <span class="comment">//2. 获取IServiceManager</span></span><br><span class="line">    <span class="built_in">ALOGI</span>(<span class="string">&quot;ServiceManager: %p&quot;</span>, sm.<span class="built_in">get</span>());</span><br><span class="line">    <span class="built_in">InitializeIcuOrDie</span>();</span><br><span class="line">    MediaPlayerService::<span class="built_in">instantiate</span>();</span><br><span class="line">    ResourceManagerService::<span class="built_in">instantiate</span>();</span><br><span class="line">    <span class="built_in">registerExtensions</span>();</span><br><span class="line">    ProcessState::<span class="built_in">self</span>()-&gt;<span class="built_in">startThreadPool</span>();</span><br><span class="line">    IPCThreadState::<span class="built_in">self</span>()-&gt;<span class="built_in">joinThreadPool</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="1-ProcessState打开binder设备"><a href="#1-ProcessState打开binder设备" class="headerlink" title="1. ProcessState打开binder设备"></a>1. ProcessState打开binder设备</h2><p>ProcessState是一个进程相关的对象，一个对象只有一个ProcessState。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\ProcessState.cpp</span></span><br><span class="line"><span class="function">sp&lt;ProcessState&gt; <span class="title">ProcessState::self</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Mutex::Autolock _l(gProcessMutex);  <span class="comment">//采用单例模式，每个进程保证只有一个ProcessState</span></span><br><span class="line">    <span class="keyword">if</span> (gProcess != <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> gProcess;</span><br><span class="line">    &#125;</span><br><span class="line">    gProcess = <span class="keyword">new</span> <span class="built_in">ProcessState</span>(<span class="string">&quot;/dev/binder&quot;</span>);   <span class="comment">//构造函数传入了binder设备的路径</span></span><br><span class="line">    <span class="keyword">return</span> gProcess;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ProcessState::<span class="built_in">ProcessState</span>(<span class="type">const</span> <span class="type">char</span> *driver)</span><br><span class="line">    : <span class="built_in">mDriverName</span>(<span class="built_in">String8</span>(driver))</span><br><span class="line">    , <span class="built_in">mDriverFD</span>(<span class="built_in">open_driver</span>(driver))  <span class="comment">//打开binder设备, mDriverFD成员变量就是binder设备的文件描述符</span></span><br><span class="line">    ......</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span> (mDriverFD &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// mmap the binder, providing a chunk of virtual address space to receive transactions.</span></span><br><span class="line">        mVMStart = <span class="built_in">mmap</span>(<span class="number">0</span>, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span> (mVMStart == MAP_FAILED) &#123;</span><br><span class="line">            <span class="comment">// *sigh*</span></span><br><span class="line">            <span class="built_in">ALOGE</span>(<span class="string">&quot;Using /dev/binder failed: unable to mmap transaction memory.\n&quot;</span>);</span><br><span class="line">            <span class="built_in">close</span>(mDriverFD);</span><br><span class="line">            mDriverFD = <span class="number">-1</span>;</span><br><span class="line">            mDriverName.<span class="built_in">clear</span>();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>ProcessState构造函数中，调用mmap把binder设备内核空间的一段内存映射到用户空间。mmap的具体作用跟设备的实现有关系。<br>关于mmap的介绍可以参考这篇文章：<a target="_blank" rel="noopener external nofollow noreferrer" href="https://blog.csdn.net/DLUTBruceZhang/article/details/9080173">Linux 内存映射函数 mmap（）函数详解
</a></p>
<p>现在看下open_driver是如何打开binder设备的。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">static</span> <span class="type">int</span> <span class="title">open_driver</span><span class="params">(<span class="type">const</span> <span class="type">char</span> *driver)</span>  <span class="comment">//driver参数指的就是&quot;/dev/binder&quot;</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> fd = <span class="built_in">open</span>(driver, O_RDWR | O_CLOEXEC);  <span class="comment">//系统调用open打开binder设备</span></span><br><span class="line">    <span class="keyword">if</span> (fd &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">//通过ioctl获取binder设备的协议版本号。</span></span><br><span class="line">        <span class="type">int</span> vers = <span class="number">0</span>;</span><br><span class="line">        <span class="type">status_t</span> result = <span class="built_in">ioctl</span>(fd, BINDER_VERSION, &amp;vers);</span><br><span class="line">        <span class="keyword">if</span> (result == <span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="built_in">ALOGE</span>(<span class="string">&quot;Binder ioctl to obtain version failed: %s&quot;</span>, <span class="built_in">strerror</span>(errno));</span><br><span class="line">            <span class="built_in">close</span>(fd);</span><br><span class="line">            fd = <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//比较应用端和binder内核驱动的版本号是否相同</span></span><br><span class="line">        <span class="keyword">if</span> (result != <span class="number">0</span> || vers != BINDER_CURRENT_PROTOCOL_VERSION) &#123;</span><br><span class="line">          <span class="built_in">ALOGE</span>(<span class="string">&quot;Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d&quot;</span>,</span><br><span class="line">                vers, BINDER_CURRENT_PROTOCOL_VERSION, result);</span><br><span class="line">            <span class="built_in">close</span>(fd);</span><br><span class="line">            fd = <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="type">size_t</span> maxThreads = DEFAULT_MAX_BINDER_THREADS;</span><br><span class="line">        <span class="comment">//设置支持的最大线程数15</span></span><br><span class="line">        result = <span class="built_in">ioctl</span>(fd, BINDER_SET_MAX_THREADS, &amp;maxThreads);</span><br><span class="line">        <span class="keyword">if</span> (result == <span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="built_in">ALOGE</span>(<span class="string">&quot;Binder ioctl to set max threads failed: %s&quot;</span>, <span class="built_in">strerror</span>(errno));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">ALOGW</span>(<span class="string">&quot;Opening &#x27;%s&#x27; failed: %s\n&quot;</span>, driver, <span class="built_in">strerror</span>(errno));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> fd;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由此可以看出打开binder设备的操作还是很简单的。</p>
<h2 id="2-获取-IServiceManager"><a href="#2-获取-IServiceManager" class="headerlink" title="2. 获取 IServiceManager"></a>2. 获取 IServiceManager</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\IServiceManager.cpp</span></span><br><span class="line"><span class="function">sp&lt;IServiceManager&gt; <span class="title">defaultServiceManager</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;   <span class="comment">//依然是单例模式</span></span><br><span class="line">    <span class="keyword">if</span> (gDefaultServiceManager != <span class="literal">NULL</span>) <span class="keyword">return</span> gDefaultServiceManager;</span><br><span class="line">    &#123;</span><br><span class="line">        AutoMutex _l(gDefaultServiceManagerLock);</span><br><span class="line">        <span class="keyword">while</span> (gDefaultServiceManager == <span class="literal">NULL</span>) &#123;</span><br><span class="line">            gDefaultServiceManager = <span class="built_in">interface_cast</span>&lt;IServiceManager&gt;(</span><br><span class="line">                ProcessState::<span class="built_in">self</span>()-&gt;<span class="built_in">getContextObject</span>(<span class="literal">NULL</span>));</span><br><span class="line">            <span class="keyword">if</span> (gDefaultServiceManager == <span class="literal">NULL</span>)</span><br><span class="line">                <span class="built_in">sleep</span>(<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> gDefaultServiceManager;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>ProcessState::self()-&gt;getContextObject(NULL)最终返回的是 new BpBinder(0); ，其中0表示的就是ServiceManager在binder系统中的标识。</p>
<p>interface_cast的定义如下，是一个模板函数</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\include\binder\IInterface.h</span></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> INTERFACE&gt;</span></span><br><span class="line"><span class="function"><span class="keyword">inline</span> sp&lt;INTERFACE&gt; <span class="title">interface_cast</span><span class="params">(<span class="type">const</span> sp&lt;IBinder&gt;&amp; obj)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> INTERFACE::<span class="built_in">asInterface</span>(obj);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//替换模板参数后就是如下形式：</span></span><br><span class="line"><span class="function"><span class="keyword">inline</span> sp&lt;IServiceManager&gt; <span class="title">interface_cast</span><span class="params">(<span class="type">const</span> sp&lt;IBinder&gt;&amp; obj)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> IServiceManager::<span class="built_in">asInterface</span>(obj);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以最终调用的是IServiceManager::asInterface(new BpBinder(0))，所以需要再分析一下IServiceManager::asInterface函数。</p>
<p>看一下IServiceManager的定义，非常简单：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\include\binder\IServiceManager.h</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">IServiceManager</span> : <span class="keyword">public</span> IInterface</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">DECLARE_META_INTERFACE</span>(ServiceManager)</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> sp&lt;IBinder&gt; <span class="title">getService</span><span class="params">( <span class="type">const</span> String16&amp; name)</span> <span class="type">const</span> </span>= <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> sp&lt;IBinder&gt; <span class="title">checkService</span><span class="params">( <span class="type">const</span> String16&amp; name)</span> <span class="type">const</span> </span>= <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="type">status_t</span>    <span class="title">addService</span><span class="params">( <span class="type">const</span> String16&amp; name, <span class="type">const</span> sp&lt;IBinder&gt;&amp; service,</span></span></span><br><span class="line"><span class="params"><span class="function">                                            <span class="type">bool</span> allowIsolated = <span class="literal">false</span>)</span> </span>= <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> Vector&lt;String16&gt;    <span class="title">listServices</span><span class="params">()</span> </span>= <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">enum</span> &#123;</span><br><span class="line">        GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,</span><br><span class="line">        CHECK_SERVICE_TRANSACTION,</span><br><span class="line">        ADD_SERVICE_TRANSACTION,</span><br><span class="line">        LIST_SERVICES_TRANSACTION,</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="DECLARE-META-INTERFACE宏"><a href="#DECLARE-META-INTERFACE宏" class="headerlink" title="DECLARE_META_INTERFACE宏"></a>DECLARE_META_INTERFACE宏</h3><p>其中DECLARE_META_INTERFACE是个宏定义，与IMPLEMENT_META_INTERFACE宏配合使用，是谷歌提供的用于native service层对接binder的两个模板宏：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\include\binder\IInterface.h</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> DECLARE_META_INTERFACE(INTERFACE)                               \</span></span><br><span class="line"><span class="meta">    static const ::android::String16 descriptor;                        \</span></span><br><span class="line"><span class="meta">    static ::android::sp<span class="string">&lt;I##INTERFACE&gt;</span> asInterface(                     \</span></span><br><span class="line"><span class="meta">            const ::android::sp<span class="string">&lt;::android::IBinder&gt;</span>&amp; obj);              \</span></span><br><span class="line"><span class="meta">    virtual const ::android::String16&amp; getInterfaceDescriptor() const;  \</span></span><br><span class="line"><span class="meta">    I##INTERFACE();                                                     \</span></span><br><span class="line"><span class="meta">    virtual ~I##INTERFACE();                                            \</span></span><br></pre></td></tr></table></figure>

<p>宏的参数替换成 ServiceManager 后，可以得到IServiceManager类的头文件声明：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\include\binder\IServiceManager.h</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">IServiceManager</span> : <span class="keyword">public</span> IInterface</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="comment">//DECLARE_META_INTERFACE(INTERFACE) 宏定义展开如下</span></span><br><span class="line">    <span class="type">static</span> <span class="type">const</span> ::android::String16 descriptor;</span><br><span class="line">    <span class="type">static</span> ::<span class="function">android::sp&lt;IServiceManager&gt; <span class="title">asInterface</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">            <span class="type">const</span> ::android::sp&lt;::android::IBinder&gt;&amp; obj)</span></span>;</span><br><span class="line">    <span class="keyword">virtual</span> <span class="type">const</span> ::<span class="function">android::String16&amp; <span class="title">getInterfaceDescriptor</span><span class="params">()</span> <span class="type">const</span></span>;</span><br><span class="line">    <span class="built_in">IServiceManager</span>();</span><br><span class="line">    <span class="keyword">virtual</span> ~<span class="built_in">IServiceManager</span>();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> sp&lt;IBinder&gt; <span class="title">getService</span><span class="params">( <span class="type">const</span> String16&amp; name)</span> <span class="type">const</span> </span>= <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> sp&lt;IBinder&gt; <span class="title">checkService</span><span class="params">( <span class="type">const</span> String16&amp; name)</span> <span class="type">const</span> </span>= <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="type">status_t</span>    <span class="title">addService</span><span class="params">( <span class="type">const</span> String16&amp; name, <span class="type">const</span> sp&lt;IBinder&gt;&amp; service,</span></span></span><br><span class="line"><span class="params"><span class="function">                                            <span class="type">bool</span> allowIsolated = <span class="literal">false</span>)</span> </span>= <span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> Vector&lt;String16&gt;    <span class="title">listServices</span><span class="params">()</span> </span>= <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">enum</span> &#123;</span><br><span class="line">        GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,</span><br><span class="line">        CHECK_SERVICE_TRANSACTION,</span><br><span class="line">        ADD_SERVICE_TRANSACTION,</span><br><span class="line">        LIST_SERVICES_TRANSACTION,</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="IMPLEMENT-META-INTERFACE宏"><a href="#IMPLEMENT-META-INTERFACE宏" class="headerlink" title="IMPLEMENT_META_INTERFACE宏"></a>IMPLEMENT_META_INTERFACE宏</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\include\binder\IInterface.h</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \</span></span><br><span class="line"><span class="meta">    const ::android::String16 I##INTERFACE::descriptor(NAME);           \</span></span><br><span class="line"><span class="meta">    const ::android::String16&amp;                                          \</span></span><br><span class="line"><span class="meta">            I##INTERFACE::getInterfaceDescriptor() const &#123;              \</span></span><br><span class="line"><span class="meta">        return I##INTERFACE::descriptor;                                \</span></span><br><span class="line"><span class="meta">    &#125;                                                                   \</span></span><br><span class="line"><span class="meta">    ::android::sp<span class="string">&lt;I##INTERFACE&gt;</span> I##INTERFACE::asInterface(              \</span></span><br><span class="line"><span class="meta">            const ::android::sp<span class="string">&lt;::android::IBinder&gt;</span>&amp; obj)               \</span></span><br><span class="line"><span class="meta">    &#123;                                                                   \</span></span><br><span class="line"><span class="meta">        ::android::sp<span class="string">&lt;I##INTERFACE&gt;</span> intr;                               \</span></span><br><span class="line"><span class="meta">        <span class="keyword">if</span> (obj != NULL) &#123;                                              \</span></span><br><span class="line"><span class="meta">            intr = static_cast<span class="string">&lt;I##INTERFACE*&gt;</span>(                          \</span></span><br><span class="line"><span class="meta">                obj-&gt;queryLocalInterface(                               \</span></span><br><span class="line"><span class="meta">                        I##INTERFACE::descriptor).get());               \</span></span><br><span class="line"><span class="meta">            <span class="keyword">if</span> (intr == NULL) &#123;                                         \</span></span><br><span class="line"><span class="meta">                intr = new Bp##INTERFACE(obj);                          \</span></span><br><span class="line"><span class="meta">            &#125;                                                           \</span></span><br><span class="line"><span class="meta">        &#125;                                                               \</span></span><br><span class="line"><span class="meta">        return intr;                                                    \</span></span><br><span class="line"><span class="meta">    &#125;                                                                   \</span></span><br><span class="line"><span class="meta">    I##INTERFACE::I##INTERFACE() &#123; &#125;                                    \</span></span><br><span class="line"><span class="meta">    I##INTERFACE::~I##INTERFACE() &#123; &#125;                                   \</span></span><br></pre></td></tr></table></figure>

<p>再看下IServiceManager.cpp中IMPLEMENT_META_INTERFACE宏的使用</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\IServiceManager.cpp</span></span><br><span class="line"><span class="built_in">IMPLEMENT_META_INTERFACE</span>(ServiceManager, <span class="string">&quot;android.os.IServiceManager&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>把宏定义展开后，IServiceManager.cpp源码如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// IMPLEMENT_META_INTERFACE(INTERFACE, NAME)宏定义展开代码如下：</span></span><br><span class="line">    <span class="type">const</span> ::<span class="function">android::String16 <span class="title">IServiceManager::descriptor</span><span class="params">(<span class="string">&quot;android.os.IServiceManager&quot;</span>)</span></span>;</span><br><span class="line">    <span class="type">const</span> ::<span class="function">android::String16&amp; <span class="title">IServiceManager::getInterfaceDescriptor</span><span class="params">()</span> <span class="type">const</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> IServiceManager::descriptor;</span><br><span class="line">    &#125;</span><br><span class="line">    ::<span class="function">android::sp&lt;IServiceManager&gt; <span class="title">IServiceManager::asInterface</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">            <span class="type">const</span> ::android::sp&lt;::android::IBinder&gt;&amp; obj)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        ::android::sp&lt;IServiceManager&gt; intr;</span><br><span class="line">        <span class="keyword">if</span> (obj != <span class="literal">NULL</span>) &#123;</span><br><span class="line">            intr = <span class="built_in">static_cast</span>&lt;IServiceManager*&gt;(</span><br><span class="line">                obj-&gt;<span class="built_in">queryLocalInterface</span>(IServiceManagerE::descriptor).<span class="built_in">get</span>());</span><br><span class="line">            <span class="keyword">if</span> (intr == <span class="literal">NULL</span>) &#123;</span><br><span class="line">                intr = <span class="keyword">new</span> <span class="built_in">BpServiceManager</span>(obj);  <span class="comment">//最终是创建了一个BpServiceManager对象</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> intr;</span><br><span class="line">    &#125;</span><br><span class="line">    IServiceManager::<span class="built_in">IServiceManager</span>() &#123; &#125;</span><br><span class="line">    IServiceManager::~<span class="built_in">IServiceManager</span>() &#123; &#125;</span><br></pre></td></tr></table></figure>

<h3 id="获取IServiceManager小结"><a href="#获取IServiceManager小结" class="headerlink" title="获取IServiceManager小结"></a>获取IServiceManager小结</h3><p>获取IServiceManager的代码可以使用如下代码来等价的表示：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//简化版代码</span></span><br><span class="line"><span class="function">sp&lt;IServiceManager&gt; <span class="title">defaultServiceManager</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (gDefaultServiceManager != <span class="literal">NULL</span>) <span class="keyword">return</span> gDefaultServiceManager;</span><br><span class="line"></span><br><span class="line">    &#123;</span><br><span class="line">        AutoMutex _l(gDefaultServiceManagerLock);</span><br><span class="line">        <span class="keyword">while</span> (gDefaultServiceManager == <span class="literal">NULL</span>) &#123;</span><br><span class="line">            gDefaultServiceManager = <span class="keyword">new</span> <span class="built_in">BpServiceManager</span>(<span class="keyword">new</span> <span class="built_in">BpBinder</span>(<span class="number">0</span>));</span><br><span class="line">            <span class="keyword">if</span> (gDefaultServiceManager == <span class="literal">NULL</span>)</span><br><span class="line">                <span class="built_in">sleep</span>(<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> gDefaultServiceManager;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从上面代码可以看出获取的IServiceManager就是BpServiceManager对象，BpServiceManager的构造函数需要一个BpBinder对象。这两个类的作用我们在后面详细介绍。</p>
<h2 id="3-addService流程分析"><a href="#3-addService流程分析" class="headerlink" title="3. addService流程分析"></a>3. addService流程分析</h2><p>再回顾下上面两个章节内容：</p>
<ol>
<li>mediaserver进程首先创建了一个ProcessState，在ProcessState的构造函数中打开了binder设备；</li>
<li>获取IServiceManager（就是BpServiceManager对象），然后就可以与ServiceManager进行binder通信了。</li>
</ol>
<p>通过上面介绍的两点，我们就可以推测出来，BpServiceManager肯定要使用ProcessState才能进行binder通信。实际情况也的确如此，BpServiceManager通过BpBinder对象来使用ProcessState。</p>
<p>首先看下MediaServer是怎么调用addService把多媒体服务添加到ServiceManager中的：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\av\media\mediaserver\main_mediaserver.cpp</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">int</span> argc __unused, <span class="type">char</span> **argv __unused)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">signal</span>(SIGPIPE, SIG_IGN);</span><br><span class="line"></span><br><span class="line">    <span class="function">sp&lt;ProcessState&gt; <span class="title">proc</span><span class="params">(ProcessState::self())</span></span>;</span><br><span class="line">    <span class="function">sp&lt;IServiceManager&gt; <span class="title">sm</span><span class="params">(defaultServiceManager())</span></span>;</span><br><span class="line">    <span class="built_in">ALOGI</span>(<span class="string">&quot;ServiceManager: %p&quot;</span>, sm.<span class="built_in">get</span>());</span><br><span class="line">    <span class="built_in">InitializeIcuOrDie</span>();</span><br><span class="line">    MediaPlayerService::<span class="built_in">instantiate</span>();  <span class="comment">//初始化MediaPlayerService</span></span><br><span class="line">    ResourceManagerService::<span class="built_in">instantiate</span>();</span><br><span class="line">    <span class="built_in">registerExtensions</span>();</span><br><span class="line">    ProcessState::<span class="built_in">self</span>()-&gt;<span class="built_in">startThreadPool</span>();</span><br><span class="line">    IPCThreadState::<span class="built_in">self</span>()-&gt;<span class="built_in">joinThreadPool</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//frameworks\av\media\libmediaplayerservice\MediaPlayerService.cpp</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">MediaPlayerService::instantiate</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//defaultServiceManager返回的就是BpServiceManager，就是上面的分析过程。</span></span><br><span class="line">    <span class="comment">//new了一个MediaPlayerService，然后通过addService添加binder服务</span></span><br><span class="line">    <span class="built_in">defaultServiceManager</span>()-&gt;<span class="built_in">addService</span>(</span><br><span class="line">            <span class="built_in">String16</span>(<span class="string">&quot;media.player&quot;</span>), <span class="keyword">new</span> <span class="built_in">MediaPlayerService</span>());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="BpServiceManager类"><a href="#BpServiceManager类" class="headerlink" title="BpServiceManager类"></a>BpServiceManager类</h3><p>BpServiceManager就是binder跨进程通信机制的C/S架构的client端，属于业务层，定义在frameworks\native\libs\binder\IServiceManager.cpp文件中。首先看下BpServiceManager相关联的binder家族类图：</p>
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="510px" preserveAspectRatio="none" style="width:476px;height:510px;background:#FFFFFF;" version="1.1" viewBox="0 0 476 510" width="476px" zoomAndPan="magnify"><defs/><g><!--class IBinder--><g id="elem_IBinder"><rect codeLine="2" fill="#F1F1F1" height="64.2969" id="IBinder" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="86" x="36.5" y="115"/><ellipse cx="52.85" cy="131" fill="#B4A7E5" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M53.8031,127.7813 L55.5219,127.7813 C55.9125,127.7813 56.1,127.75 56.225,127.6719 C56.4906,127.5156 56.6313,127.2344 56.6313,126.9375 C56.6313,126.6719 56.5219,126.4063 56.2875,126.2344 C56.1156,126.125 55.975,126.0938 55.5219,126.0938 L50.3813,126.0938 C49.9438,126.0938 49.8188,126.1094 49.6625,126.2031 C49.4125,126.3594 49.2563,126.6563 49.2563,126.9375 C49.2563,127.2188 49.3969,127.4688 49.6156,127.6406 C49.7719,127.75 49.9594,127.7813 50.3813,127.7813 L52.1,127.7813 L52.1,134.2969 L50.3813,134.2969 C49.9438,134.2969 49.8188,134.3125 49.6625,134.4219 C49.4125,134.5781 49.2563,134.8594 49.2563,135.1563 C49.2563,135.4063 49.3969,135.6719 49.6156,135.8281 C49.7719,135.9531 49.975,136 50.3813,136 L55.5219,136 C56.2719,136 56.6313,135.7188 56.6313,135.1563 C56.6313,134.875 56.5219,134.625 56.2875,134.4531 C56.1156,134.3281 55.975,134.2969 55.5219,134.2969 L53.8031,134.2969 L53.8031,127.7813 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" font-style="italic" lengthAdjust="spacing" textLength="51" x="67.15" y="135.8467">IBinder</text><line style="stroke:#181818;stroke-width:0.5;" x1="37.5" x2="121.5" y1="147" y2="147"/><ellipse cx="47.5" cy="160.6484" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="60" x="56.5" y="163.9951">transact</text><line style="stroke:#181818;stroke-width:0.5;" x1="37.5" x2="121.5" y1="171.2969" y2="171.2969"/></g><!--class RefBase--><g id="elem_RefBase"><rect fill="#F1F1F1" height="48" id="RefBase" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="91" x="192" y="7"/><ellipse cx="207" cy="23" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M209.3438,18.6719 C208.4063,18.2344 207.8125,18.0938 206.9375,18.0938 C204.3125,18.0938 202.3125,20.1719 202.3125,22.8906 L202.3125,24.0156 C202.3125,26.5938 204.4219,28.4844 207.3125,28.4844 C208.5313,28.4844 209.6875,28.1875 210.4375,27.6406 C211.0156,27.2344 211.3438,26.7813 211.3438,26.3906 C211.3438,25.9375 210.9531,25.5469 210.4844,25.5469 C210.2656,25.5469 210.0625,25.625 209.875,25.8125 C209.4219,26.2969 209.4219,26.2969 209.2344,26.3906 C208.8125,26.6563 208.125,26.7813 207.3594,26.7813 C205.3125,26.7813 204.0156,25.6875 204.0156,23.9844 L204.0156,22.8906 C204.0156,21.1094 205.2656,19.7969 207,19.7969 C207.5781,19.7969 208.1875,19.9531 208.6563,20.2031 C209.1406,20.4844 209.3125,20.7031 209.4063,21.1094 C209.4688,21.5156 209.5,21.6406 209.6406,21.7656 C209.7813,21.9063 210.0156,22.0156 210.2344,22.0156 C210.5,22.0156 210.7656,21.875 210.9375,21.6563 C211.0469,21.5 211.0781,21.3125 211.0781,20.8906 L211.0781,19.4688 C211.0781,19.0313 211.0625,18.9063 210.9688,18.75 C210.8125,18.4844 210.5313,18.3438 210.2344,18.3438 C209.9375,18.3438 209.7344,18.4375 209.5156,18.75 L209.3438,18.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="59" x="221" y="27.8467">RefBase</text><line style="stroke:#181818;stroke-width:0.5;" x1="193" x2="282" y1="39" y2="39"/><line style="stroke:#181818;stroke-width:0.5;" x1="193" x2="282" y1="47" y2="47"/></g><!--class BpBinder--><g id="elem_BpBinder"><rect fill="#F1F1F1" height="48" id="BpBinder" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="99" x="30" y="239"/><ellipse cx="45" cy="255" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M47.3438,250.6719 C46.4063,250.2344 45.8125,250.0938 44.9375,250.0938 C42.3125,250.0938 40.3125,252.1719 40.3125,254.8906 L40.3125,256.0156 C40.3125,258.5938 42.4219,260.4844 45.3125,260.4844 C46.5313,260.4844 47.6875,260.1875 48.4375,259.6406 C49.0156,259.2344 49.3438,258.7813 49.3438,258.3906 C49.3438,257.9375 48.9531,257.5469 48.4844,257.5469 C48.2656,257.5469 48.0625,257.625 47.875,257.8125 C47.4219,258.2969 47.4219,258.2969 47.2344,258.3906 C46.8125,258.6563 46.125,258.7813 45.3594,258.7813 C43.3125,258.7813 42.0156,257.6875 42.0156,255.9844 L42.0156,254.8906 C42.0156,253.1094 43.2656,251.7969 45,251.7969 C45.5781,251.7969 46.1875,251.9531 46.6563,252.2031 C47.1406,252.4844 47.3125,252.7031 47.4063,253.1094 C47.4688,253.5156 47.5,253.6406 47.6406,253.7656 C47.7813,253.9063 48.0156,254.0156 48.2344,254.0156 C48.5,254.0156 48.7656,253.875 48.9375,253.6563 C49.0469,253.5 49.0781,253.3125 49.0781,252.8906 L49.0781,251.4688 C49.0781,251.0313 49.0625,250.9063 48.9688,250.75 C48.8125,250.4844 48.5313,250.3438 48.2344,250.3438 C47.9375,250.3438 47.7344,250.4375 47.5156,250.75 L47.3438,250.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="67" x="59" y="259.8467">BpBinder</text><line style="stroke:#181818;stroke-width:0.5;" x1="31" x2="128" y1="271" y2="271"/><line style="stroke:#181818;stroke-width:0.5;" x1="31" x2="128" y1="279" y2="279"/></g><!--class IPCThreadState--><g id="elem_IPCThreadState"><rect fill="#F1F1F1" height="48" id="IPCThreadState" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="145" x="7" y="347"/><ellipse cx="22" cy="363" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M24.3438,358.6719 C23.4063,358.2344 22.8125,358.0938 21.9375,358.0938 C19.3125,358.0938 17.3125,360.1719 17.3125,362.8906 L17.3125,364.0156 C17.3125,366.5938 19.4219,368.4844 22.3125,368.4844 C23.5313,368.4844 24.6875,368.1875 25.4375,367.6406 C26.0156,367.2344 26.3438,366.7813 26.3438,366.3906 C26.3438,365.9375 25.9531,365.5469 25.4844,365.5469 C25.2656,365.5469 25.0625,365.625 24.875,365.8125 C24.4219,366.2969 24.4219,366.2969 24.2344,366.3906 C23.8125,366.6563 23.125,366.7813 22.3594,366.7813 C20.3125,366.7813 19.0156,365.6875 19.0156,363.9844 L19.0156,362.8906 C19.0156,361.1094 20.2656,359.7969 22,359.7969 C22.5781,359.7969 23.1875,359.9531 23.6563,360.2031 C24.1406,360.4844 24.3125,360.7031 24.4063,361.1094 C24.4688,361.5156 24.5,361.6406 24.6406,361.7656 C24.7813,361.9063 25.0156,362.0156 25.2344,362.0156 C25.5,362.0156 25.7656,361.875 25.9375,361.6563 C26.0469,361.5 26.0781,361.3125 26.0781,360.8906 L26.0781,359.4688 C26.0781,359.0313 26.0625,358.9063 25.9688,358.75 C25.8125,358.4844 25.5313,358.3438 25.2344,358.3438 C24.9375,358.3438 24.7344,358.4375 24.5156,358.75 L24.3438,358.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="113" x="36" y="367.8467">IPCThreadState</text><line style="stroke:#181818;stroke-width:0.5;" x1="8" x2="151" y1="379" y2="379"/><line style="stroke:#181818;stroke-width:0.5;" x1="8" x2="151" y1="387" y2="387"/></g><!--class ProcessState--><g id="elem_ProcessState"><rect fill="#F1F1F1" height="48" id="ProcessState" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="127" x="16" y="455"/><ellipse cx="31" cy="471" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M33.3438,466.6719 C32.4063,466.2344 31.8125,466.0938 30.9375,466.0938 C28.3125,466.0938 26.3125,468.1719 26.3125,470.8906 L26.3125,472.0156 C26.3125,474.5938 28.4219,476.4844 31.3125,476.4844 C32.5313,476.4844 33.6875,476.1875 34.4375,475.6406 C35.0156,475.2344 35.3438,474.7813 35.3438,474.3906 C35.3438,473.9375 34.9531,473.5469 34.4844,473.5469 C34.2656,473.5469 34.0625,473.625 33.875,473.8125 C33.4219,474.2969 33.4219,474.2969 33.2344,474.3906 C32.8125,474.6563 32.125,474.7813 31.3594,474.7813 C29.3125,474.7813 28.0156,473.6875 28.0156,471.9844 L28.0156,470.8906 C28.0156,469.1094 29.2656,467.7969 31,467.7969 C31.5781,467.7969 32.1875,467.9531 32.6563,468.2031 C33.1406,468.4844 33.3125,468.7031 33.4063,469.1094 C33.4688,469.5156 33.5,469.6406 33.6406,469.7656 C33.7813,469.9063 34.0156,470.0156 34.2344,470.0156 C34.5,470.0156 34.7656,469.875 34.9375,469.6563 C35.0469,469.5 35.0781,469.3125 35.0781,468.8906 L35.0781,467.4688 C35.0781,467.0313 35.0625,466.9063 34.9688,466.75 C34.8125,466.4844 34.5313,466.3438 34.2344,466.3438 C33.9375,466.3438 33.7344,466.4375 33.5156,466.75 L33.3438,466.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="95" x="45" y="475.8467">ProcessState</text><line style="stroke:#181818;stroke-width:0.5;" x1="17" x2="142" y1="487" y2="487"/><line style="stroke:#181818;stroke-width:0.5;" x1="17" x2="142" y1="495" y2="495"/></g><!--class IServiceManager--><g id="elem_IServiceManager"><rect codeLine="9" fill="#F1F1F1" height="48" id="IServiceManager" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="152" x="317.5" y="239"/><ellipse cx="332.5" cy="255" fill="#B4A7E5" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M333.4531,251.7813 L335.1719,251.7813 C335.5625,251.7813 335.75,251.75 335.875,251.6719 C336.1406,251.5156 336.2813,251.2344 336.2813,250.9375 C336.2813,250.6719 336.1719,250.4063 335.9375,250.2344 C335.7656,250.125 335.625,250.0938 335.1719,250.0938 L330.0313,250.0938 C329.5938,250.0938 329.4688,250.1094 329.3125,250.2031 C329.0625,250.3594 328.9063,250.6563 328.9063,250.9375 C328.9063,251.2188 329.0469,251.4688 329.2656,251.6406 C329.4219,251.75 329.6094,251.7813 330.0313,251.7813 L331.75,251.7813 L331.75,258.2969 L330.0313,258.2969 C329.5938,258.2969 329.4688,258.3125 329.3125,258.4219 C329.0625,258.5781 328.9063,258.8594 328.9063,259.1563 C328.9063,259.4063 329.0469,259.6719 329.2656,259.8281 C329.4219,259.9531 329.625,260 330.0313,260 L335.1719,260 C335.9219,260 336.2813,259.7188 336.2813,259.1563 C336.2813,258.875 336.1719,258.625 335.9375,258.4531 C335.7656,258.3281 335.625,258.2969 335.1719,258.2969 L333.4531,258.2969 L333.4531,251.7813 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" font-style="italic" lengthAdjust="spacing" textLength="120" x="346.5" y="259.8467">IServiceManager</text><line style="stroke:#181818;stroke-width:0.5;" x1="318.5" x2="468.5" y1="271" y2="271"/><line style="stroke:#181818;stroke-width:0.5;" x1="318.5" x2="468.5" y1="279" y2="279"/></g><!--class IInterface--><g id="elem_IInterface"><rect codeLine="11" fill="#F1F1F1" height="64.2969" id="IInterface" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="100" x="352.5" y="115"/><ellipse cx="367.5" cy="131" fill="#B4A7E5" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M368.4531,127.7813 L370.1719,127.7813 C370.5625,127.7813 370.75,127.75 370.875,127.6719 C371.1406,127.5156 371.2813,127.2344 371.2813,126.9375 C371.2813,126.6719 371.1719,126.4063 370.9375,126.2344 C370.7656,126.125 370.625,126.0938 370.1719,126.0938 L365.0313,126.0938 C364.5938,126.0938 364.4688,126.1094 364.3125,126.2031 C364.0625,126.3594 363.9063,126.6563 363.9063,126.9375 C363.9063,127.2188 364.0469,127.4688 364.2656,127.6406 C364.4219,127.75 364.6094,127.7813 365.0313,127.7813 L366.75,127.7813 L366.75,134.2969 L365.0313,134.2969 C364.5938,134.2969 364.4688,134.3125 364.3125,134.4219 C364.0625,134.5781 363.9063,134.8594 363.9063,135.1563 C363.9063,135.4063 364.0469,135.6719 364.2656,135.8281 C364.4219,135.9531 364.625,136 365.0313,136 L370.1719,136 C370.9219,136 371.2813,135.7188 371.2813,135.1563 C371.2813,134.875 371.1719,134.625 370.9375,134.4531 C370.7656,134.3281 370.625,134.2969 370.1719,134.2969 L368.4531,134.2969 L368.4531,127.7813 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" font-style="italic" lengthAdjust="spacing" textLength="68" x="381.5" y="135.8467">IInterface</text><line style="stroke:#181818;stroke-width:0.5;" x1="353.5" x2="451.5" y1="147" y2="147"/><ellipse cx="363.5" cy="160.6484" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" text-decoration="underline" textLength="62" x="372.5" y="163.9951">asBinder</text><line style="stroke:#181818;stroke-width:0.5;" x1="353.5" x2="451.5" y1="171.2969" y2="171.2969"/></g><!--class BpInterface--><g id="elem_BpInterface"><rect codeLine="15" fill="#F1F1F1" height="48" id="BpInterface" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="222" x="230.5" y="347"/><ellipse cx="245.5" cy="363" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M247.8438,358.6719 C246.9063,358.2344 246.3125,358.0938 245.4375,358.0938 C242.8125,358.0938 240.8125,360.1719 240.8125,362.8906 L240.8125,364.0156 C240.8125,366.5938 242.9219,368.4844 245.8125,368.4844 C247.0313,368.4844 248.1875,368.1875 248.9375,367.6406 C249.5156,367.2344 249.8438,366.7813 249.8438,366.3906 C249.8438,365.9375 249.4531,365.5469 248.9844,365.5469 C248.7656,365.5469 248.5625,365.625 248.375,365.8125 C247.9219,366.2969 247.9219,366.2969 247.7344,366.3906 C247.3125,366.6563 246.625,366.7813 245.8594,366.7813 C243.8125,366.7813 242.5156,365.6875 242.5156,363.9844 L242.5156,362.8906 C242.5156,361.1094 243.7656,359.7969 245.5,359.7969 C246.0781,359.7969 246.6875,359.9531 247.1563,360.2031 C247.6406,360.4844 247.8125,360.7031 247.9063,361.1094 C247.9688,361.5156 248,361.6406 248.1406,361.7656 C248.2813,361.9063 248.5156,362.0156 248.7344,362.0156 C249,362.0156 249.2656,361.875 249.4375,361.6563 C249.5469,361.5 249.5781,361.3125 249.5781,360.8906 L249.5781,359.4688 C249.5781,359.0313 249.5625,358.9063 249.4688,358.75 C249.3125,358.4844 249.0313,358.3438 248.7344,358.3438 C248.4375,358.3438 248.2344,358.4375 248.0156,358.75 L247.8438,358.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="86" x="259.5" y="367.8467">BpInterface</text><rect fill="#FFFFFF" height="15.9688" style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" width="102" x="353.5" y="344"/><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="100" x="354.5" y="356.1387">IServiceManager</text><line style="stroke:#181818;stroke-width:0.5;" x1="231.5" x2="451.5" y1="379" y2="379"/><line style="stroke:#181818;stroke-width:0.5;" x1="231.5" x2="451.5" y1="387" y2="387"/></g><!--class BpRefBase--><g id="elem_BpRefBase"><rect codeLine="22" fill="#F1F1F1" height="64.2969" id="BpRefBase" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="160" x="157.5" y="115"/><ellipse cx="194.55" cy="131" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M196.8938,126.6719 C195.9563,126.2344 195.3625,126.0938 194.4875,126.0938 C191.8625,126.0938 189.8625,128.1719 189.8625,130.8906 L189.8625,132.0156 C189.8625,134.5938 191.9719,136.4844 194.8625,136.4844 C196.0813,136.4844 197.2375,136.1875 197.9875,135.6406 C198.5656,135.2344 198.8938,134.7813 198.8938,134.3906 C198.8938,133.9375 198.5031,133.5469 198.0344,133.5469 C197.8156,133.5469 197.6125,133.625 197.425,133.8125 C196.9719,134.2969 196.9719,134.2969 196.7844,134.3906 C196.3625,134.6563 195.675,134.7813 194.9094,134.7813 C192.8625,134.7813 191.5656,133.6875 191.5656,131.9844 L191.5656,130.8906 C191.5656,129.1094 192.8156,127.7969 194.55,127.7969 C195.1281,127.7969 195.7375,127.9531 196.2063,128.2031 C196.6906,128.4844 196.8625,128.7031 196.9563,129.1094 C197.0188,129.5156 197.05,129.6406 197.1906,129.7656 C197.3313,129.9063 197.5656,130.0156 197.7844,130.0156 C198.05,130.0156 198.3156,129.875 198.4875,129.6563 C198.5969,129.5 198.6281,129.3125 198.6281,128.8906 L198.6281,127.4688 C198.6281,127.0313 198.6125,126.9063 198.5188,126.75 C198.3625,126.4844 198.0813,126.3438 197.7844,126.3438 C197.4875,126.3438 197.2844,126.4375 197.0656,126.75 L196.8938,126.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="79" x="213.45" y="135.8467">BpRefBase</text><line style="stroke:#181818;stroke-width:0.5;" x1="158.5" x2="316.5" y1="147" y2="147"/><rect fill="none" height="6" style="stroke:#C82930;stroke-width:1.0;" width="6" x="165.5" y="157.6484"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="134" x="177.5" y="163.9951">IBinder* mRemote</text><line style="stroke:#181818;stroke-width:0.5;" x1="158.5" x2="316.5" y1="171.2969" y2="171.2969"/></g><!--class BpServiceManager--><g id="elem_BpServiceManager"><rect fill="#F1F1F1" height="48" id="BpServiceManager" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="166" x="258.5" y="455"/><ellipse cx="273.5" cy="471" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M275.8438,466.6719 C274.9063,466.2344 274.3125,466.0938 273.4375,466.0938 C270.8125,466.0938 268.8125,468.1719 268.8125,470.8906 L268.8125,472.0156 C268.8125,474.5938 270.9219,476.4844 273.8125,476.4844 C275.0313,476.4844 276.1875,476.1875 276.9375,475.6406 C277.5156,475.2344 277.8438,474.7813 277.8438,474.3906 C277.8438,473.9375 277.4531,473.5469 276.9844,473.5469 C276.7656,473.5469 276.5625,473.625 276.375,473.8125 C275.9219,474.2969 275.9219,474.2969 275.7344,474.3906 C275.3125,474.6563 274.625,474.7813 273.8594,474.7813 C271.8125,474.7813 270.5156,473.6875 270.5156,471.9844 L270.5156,470.8906 C270.5156,469.1094 271.7656,467.7969 273.5,467.7969 C274.0781,467.7969 274.6875,467.9531 275.1563,468.2031 C275.6406,468.4844 275.8125,468.7031 275.9063,469.1094 C275.9688,469.5156 276,469.6406 276.1406,469.7656 C276.2813,469.9063 276.5156,470.0156 276.7344,470.0156 C277,470.0156 277.2656,469.875 277.4375,469.6563 C277.5469,469.5 277.5781,469.3125 277.5781,468.8906 L277.5781,467.4688 C277.5781,467.0313 277.5625,466.9063 277.4688,466.75 C277.3125,466.4844 277.0313,466.3438 276.7344,466.3438 C276.4375,466.3438 276.2344,466.4375 276.0156,466.75 L275.8438,466.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="134" x="287.5" y="475.8467">BpServiceManager</text><line style="stroke:#181818;stroke-width:0.5;" x1="259.5" x2="423.5" y1="487" y2="487"/><line style="stroke:#181818;stroke-width:0.5;" x1="259.5" x2="423.5" y1="495" y2="495"/></g><!--reverse link RefBase to IBinder--><g id="link_RefBase_IBinder"><path codeLine="5" d="M190.929,65.6022 C167.034,82.8432 148.71,96.064 122.508,114.969 " fill="none" id="RefBase-backto-IBinder" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="205.526,55.07,187.4183,60.7365,194.4397,70.4679,205.526,55.07" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link IBinder to BpBinder--><g id="link_IBinder_BpBinder"><path codeLine="6" d="M79.5,197.151 C79.5,216.005 79.5,221.647 79.5,238.845 " fill="none" id="IBinder-backto-BpBinder" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="79.5,179.151,73.5,197.151,85.5,197.151,79.5,179.151" style="stroke:#181818;stroke-width:1.0;"/></g><!--link BpBinder to IPCThreadState--><g id="link_BpBinder_IPCThreadState"><path codeLine="7" d="M79.5,287 C79.5,304.658 79.5,322.941 79.5,340.678 " fill="none" id="BpBinder-to-IPCThreadState" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="#181818" points="79.5,346.678,83.5,337.678,79.5,341.678,75.5,337.678,79.5,346.678" style="stroke:#181818;stroke-width:1.0;"/></g><!--link IPCThreadState to ProcessState--><g id="link_IPCThreadState_ProcessState"><path codeLine="8" d="M79.5,395 C79.5,412.6584 79.5,430.9408 79.5,448.6784 " fill="none" id="IPCThreadState-to-ProcessState" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="#181818" points="79.5,454.6784,83.5,445.6784,79.5,449.6784,75.5,445.6784,79.5,454.6784" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link RefBase to IInterface--><g id="link_RefBase_IInterface"><path codeLine="10" d="M285.6991,65.3018 C310.6531,82.5428 330.224,96.064 357.587,114.969 " fill="none" id="RefBase-backto-IInterface" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="270.89,55.07,282.2885,70.2382,289.1097,60.3654,270.89,55.07" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link IInterface to IServiceManager--><g id="link_IInterface_IServiceManager"><path codeLine="14" d="M398.6239,197.0951 C397.1349,215.9491 396.686,221.647 395.328,238.845 " fill="none" id="IInterface-backto-IServiceManager" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="400.041,179.151,392.6425,196.6227,404.6052,197.5675,400.041,179.151" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link RefBase to BpRefBase--><g id="link_RefBase_BpRefBase"><path codeLine="16" d="M237.5,73.07 C237.5,90.246 237.5,95.884 237.5,114.755 " fill="none" id="RefBase-backto-BpRefBase" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="237.5,55.07,231.5,73.07,243.5,73.07,237.5,55.07" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link BpRefBase to BpInterface--><g id="link_BpRefBase_BpInterface"><path codeLine="17" d="M258.0217,195.6279 C270.2957,223.9299 282.02,250.253 299.5,287 C309.212,307.417 320.863,330.326 329.427,346.895 " fill="none" id="BpRefBase-backto-BpInterface" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="250.86,179.114,252.5171,198.0152,263.5264,193.2407,250.86,179.114" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link IServiceManager to BpInterface--><g id="link_IServiceManager_BpInterface"><path codeLine="18" d="M374.2889,303.16 C365.6259,320.818 361.642,328.941 352.941,346.678 " fill="none" id="IServiceManager-backto-BpInterface" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="382.217,287,368.9023,300.5173,379.6756,305.8027,382.217,287" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link BpInterface to BpServiceManager--><g id="link_BpInterface_BpServiceManager"><path codeLine="19" d="M341.5,413 C341.5,430.6584 341.5,436.9408 341.5,454.6784 " fill="none" id="BpInterface-backto-BpServiceManager" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="341.5,395,335.5,413,347.5,413,341.5,395" style="stroke:#181818;stroke-width:1.0;"/></g><!--link IBinder to BpRefBase--><g id="link_IBinder_BpRefBase"><path codeLine="21" d="M122.703,147 C134.213,147 133.722,147 145.232,147 " fill="none" id="IBinder-to-BpRefBase" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="#181818" points="157.232,147,151.232,143,145.232,147,151.232,151,157.232,147" style="stroke:#181818;stroke-width:1.0;"/></g><!--SRC=[RP4x3i8m38RtdC8RKglS07K8KmSa15p02YvKWb8b4KlfoC19E01Z1qu3lGOHRKeQoEJ7R_kpCm5HhaYTSabpB71B2jhczhe-dfTxUszONXXI6Kg2LEJ5ngOh1lR5Hc6XKHfMioLb0ZN1zCovap4d_mH5sKUT0Pmda2vcwvqYtAmC6c9ZzwDOgACahRkyXp8c3W1If_ChXc3FNsdRCvSrnAXxjffvggvLC4VkKMkxp22R1efaZ2BAtcM3vH9VoA35hy2pNJBWcdmdGVJd3tZaeRWbN45tZw4eWiEI3aTxx_eD]--></g></svg>

<p>BpServiceManager的父类BpRefBase持有了BpBinder对象，BpBinder会使用IPCThreadState，而IPCThreadState又使用ProcessState。通过这张图，BpServiceManager到ProcessState的脉络就清楚了。</p>
<p>BpInterface是个模板类，会继承它的模板参数，比如在此处继承了IServiceManager。从上面的类图中可以看出BpServiceManager并没有继承IBinder，而是通过父类BpInterface的mRemote成员变量持有了BpBinder（继承自IBinder）。BpServiceManager与ServiceManager服务端的交互都是通过BpBinder来进行的。</p>
<h3 id="MediaPlayerService类"><a href="#MediaPlayerService类" class="headerlink" title="MediaPlayerService类"></a>MediaPlayerService类</h3><p>熟悉了BpServiceManager的脉络，再先看下通过addService添加的MediaPlayerService类的脉络，然后再继续分析ServiceManager的addService的流程：</p>
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="634px" preserveAspectRatio="none" style="width:333px;height:634px;background:#FFFFFF;" version="1.1" viewBox="0 0 333 634" width="333px" zoomAndPan="magnify"><defs/><g><!--class IBinder--><g id="elem_IBinder"><rect codeLine="2" fill="#F1F1F1" height="48" id="IBinder" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="83" x="32.5" y="123"/><ellipse cx="47.5" cy="139" fill="#B4A7E5" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M48.4531,135.7813 L50.1719,135.7813 C50.5625,135.7813 50.75,135.75 50.875,135.6719 C51.1406,135.5156 51.2813,135.2344 51.2813,134.9375 C51.2813,134.6719 51.1719,134.4063 50.9375,134.2344 C50.7656,134.125 50.625,134.0938 50.1719,134.0938 L45.0313,134.0938 C44.5938,134.0938 44.4688,134.1094 44.3125,134.2031 C44.0625,134.3594 43.9063,134.6563 43.9063,134.9375 C43.9063,135.2188 44.0469,135.4688 44.2656,135.6406 C44.4219,135.75 44.6094,135.7813 45.0313,135.7813 L46.75,135.7813 L46.75,142.2969 L45.0313,142.2969 C44.5938,142.2969 44.4688,142.3125 44.3125,142.4219 C44.0625,142.5781 43.9063,142.8594 43.9063,143.1563 C43.9063,143.4063 44.0469,143.6719 44.2656,143.8281 C44.4219,143.9531 44.625,144 45.0313,144 L50.1719,144 C50.9219,144 51.2813,143.7188 51.2813,143.1563 C51.2813,142.875 51.1719,142.625 50.9375,142.4531 C50.7656,142.3281 50.625,142.2969 50.1719,142.2969 L48.4531,142.2969 L48.4531,135.7813 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" font-style="italic" lengthAdjust="spacing" textLength="51" x="61.5" y="143.8467">IBinder</text><line style="stroke:#181818;stroke-width:0.5;" x1="33.5" x2="114.5" y1="155" y2="155"/><line style="stroke:#181818;stroke-width:0.5;" x1="33.5" x2="114.5" y1="163" y2="163"/></g><!--class IMediaPlayerService--><g id="elem_IMediaPlayerService"><rect codeLine="3" fill="#F1F1F1" height="48" id="IMediaPlayerService" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="176" x="150" y="247"/><ellipse cx="165" cy="263" fill="#B4A7E5" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M165.9531,259.7813 L167.6719,259.7813 C168.0625,259.7813 168.25,259.75 168.375,259.6719 C168.6406,259.5156 168.7813,259.2344 168.7813,258.9375 C168.7813,258.6719 168.6719,258.4063 168.4375,258.2344 C168.2656,258.125 168.125,258.0938 167.6719,258.0938 L162.5313,258.0938 C162.0938,258.0938 161.9688,258.1094 161.8125,258.2031 C161.5625,258.3594 161.4063,258.6563 161.4063,258.9375 C161.4063,259.2188 161.5469,259.4688 161.7656,259.6406 C161.9219,259.75 162.1094,259.7813 162.5313,259.7813 L164.25,259.7813 L164.25,266.2969 L162.5313,266.2969 C162.0938,266.2969 161.9688,266.3125 161.8125,266.4219 C161.5625,266.5781 161.4063,266.8594 161.4063,267.1563 C161.4063,267.4063 161.5469,267.6719 161.7656,267.8281 C161.9219,267.9531 162.125,268 162.5313,268 L167.6719,268 C168.4219,268 168.7813,267.7188 168.7813,267.1563 C168.7813,266.875 168.6719,266.625 168.4375,266.4531 C168.2656,266.3281 168.125,266.2969 167.6719,266.2969 L165.9531,266.2969 L165.9531,259.7813 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" font-style="italic" lengthAdjust="spacing" textLength="144" x="179" y="267.8467">IMediaPlayerService</text><line style="stroke:#181818;stroke-width:0.5;" x1="151" x2="325" y1="279" y2="279"/><line style="stroke:#181818;stroke-width:0.5;" x1="151" x2="325" y1="287" y2="287"/></g><!--class BBinder--><g id="elem_BBinder"><rect codeLine="4" fill="#F1F1F1" height="64.2969" id="BBinder" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="106" x="9" y="239"/><ellipse cx="31.65" cy="255" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M33.9938,250.6719 C33.0563,250.2344 32.4625,250.0938 31.5875,250.0938 C28.9625,250.0938 26.9625,252.1719 26.9625,254.8906 L26.9625,256.0156 C26.9625,258.5938 29.0719,260.4844 31.9625,260.4844 C33.1813,260.4844 34.3375,260.1875 35.0875,259.6406 C35.6656,259.2344 35.9938,258.7813 35.9938,258.3906 C35.9938,257.9375 35.6031,257.5469 35.1344,257.5469 C34.9156,257.5469 34.7125,257.625 34.525,257.8125 C34.0719,258.2969 34.0719,258.2969 33.8844,258.3906 C33.4625,258.6563 32.775,258.7813 32.0094,258.7813 C29.9625,258.7813 28.6656,257.6875 28.6656,255.9844 L28.6656,254.8906 C28.6656,253.1094 29.9156,251.7969 31.65,251.7969 C32.2281,251.7969 32.8375,251.9531 33.3063,252.2031 C33.7906,252.4844 33.9625,252.7031 34.0563,253.1094 C34.1188,253.5156 34.15,253.6406 34.2906,253.7656 C34.4313,253.9063 34.6656,254.0156 34.8844,254.0156 C35.15,254.0156 35.4156,253.875 35.5875,253.6563 C35.6969,253.5 35.7281,253.3125 35.7281,252.8906 L35.7281,251.4688 C35.7281,251.0313 35.7125,250.9063 35.6188,250.75 C35.4625,250.4844 35.1813,250.3438 34.8844,250.3438 C34.5875,250.3438 34.3844,250.4375 34.1656,250.75 L33.9938,250.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="57" x="47.35" y="259.8467">BBinder</text><line style="stroke:#181818;stroke-width:0.5;" x1="10" x2="114" y1="271" y2="271"/><polygon fill="none" points="20,280.6484,16,286.6484,24,286.6484" style="stroke:#1963A0;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="80" x="29" y="287.9951">onTransact</text><line style="stroke:#181818;stroke-width:0.5;" x1="10" x2="114" y1="295.2969" y2="295.2969"/></g><!--class IInterface--><g id="elem_IInterface"><rect codeLine="7" fill="#F1F1F1" height="64.2969" id="IInterface" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="102" x="175" y="115"/><ellipse cx="190" cy="131" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M192.3438,126.6719 C191.4063,126.2344 190.8125,126.0938 189.9375,126.0938 C187.3125,126.0938 185.3125,128.1719 185.3125,130.8906 L185.3125,132.0156 C185.3125,134.5938 187.4219,136.4844 190.3125,136.4844 C191.5313,136.4844 192.6875,136.1875 193.4375,135.6406 C194.0156,135.2344 194.3438,134.7813 194.3438,134.3906 C194.3438,133.9375 193.9531,133.5469 193.4844,133.5469 C193.2656,133.5469 193.0625,133.625 192.875,133.8125 C192.4219,134.2969 192.4219,134.2969 192.2344,134.3906 C191.8125,134.6563 191.125,134.7813 190.3594,134.7813 C188.3125,134.7813 187.0156,133.6875 187.0156,131.9844 L187.0156,130.8906 C187.0156,129.1094 188.2656,127.7969 190,127.7969 C190.5781,127.7969 191.1875,127.9531 191.6563,128.2031 C192.1406,128.4844 192.3125,128.7031 192.4063,129.1094 C192.4688,129.5156 192.5,129.6406 192.6406,129.7656 C192.7813,129.9063 193.0156,130.0156 193.2344,130.0156 C193.5,130.0156 193.7656,129.875 193.9375,129.6563 C194.0469,129.5 194.0781,129.3125 194.0781,128.8906 L194.0781,127.4688 C194.0781,127.0313 194.0625,126.9063 193.9688,126.75 C193.8125,126.4844 193.5313,126.3438 193.2344,126.3438 C192.9375,126.3438 192.7344,126.4375 192.5156,126.75 L192.3438,126.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="70" x="204" y="135.8467">IInterface</text><line style="stroke:#181818;stroke-width:0.5;" x1="176" x2="276" y1="147" y2="147"/><ellipse cx="186" cy="160.6484" fill="none" rx="3" ry="3" style="stroke:#038048;stroke-width:1.0;"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="62" x="195" y="163.9951">asBinder</text><line style="stroke:#181818;stroke-width:0.5;" x1="176" x2="276" y1="171.2969" y2="171.2969"/></g><!--class RefBase--><g id="elem_RefBase"><rect fill="#F1F1F1" height="48" id="RefBase" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="91" x="92.5" y="7"/><ellipse cx="107.5" cy="23" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M109.8438,18.6719 C108.9063,18.2344 108.3125,18.0938 107.4375,18.0938 C104.8125,18.0938 102.8125,20.1719 102.8125,22.8906 L102.8125,24.0156 C102.8125,26.5938 104.9219,28.4844 107.8125,28.4844 C109.0313,28.4844 110.1875,28.1875 110.9375,27.6406 C111.5156,27.2344 111.8438,26.7813 111.8438,26.3906 C111.8438,25.9375 111.4531,25.5469 110.9844,25.5469 C110.7656,25.5469 110.5625,25.625 110.375,25.8125 C109.9219,26.2969 109.9219,26.2969 109.7344,26.3906 C109.3125,26.6563 108.625,26.7813 107.8594,26.7813 C105.8125,26.7813 104.5156,25.6875 104.5156,23.9844 L104.5156,22.8906 C104.5156,21.1094 105.7656,19.7969 107.5,19.7969 C108.0781,19.7969 108.6875,19.9531 109.1563,20.2031 C109.6406,20.4844 109.8125,20.7031 109.9063,21.1094 C109.9688,21.5156 110,21.6406 110.1406,21.7656 C110.2813,21.9063 110.5156,22.0156 110.7344,22.0156 C111,22.0156 111.2656,21.875 111.4375,21.6563 C111.5469,21.5 111.5781,21.3125 111.5781,20.8906 L111.5781,19.4688 C111.5781,19.0313 111.5625,18.9063 111.4688,18.75 C111.3125,18.4844 111.0313,18.3438 110.7344,18.3438 C110.4375,18.3438 110.2344,18.4375 110.0156,18.75 L109.8438,18.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="59" x="121.5" y="27.8467">RefBase</text><line style="stroke:#181818;stroke-width:0.5;" x1="93.5" x2="182.5" y1="39" y2="39"/><line style="stroke:#181818;stroke-width:0.5;" x1="93.5" x2="182.5" y1="47" y2="47"/></g><!--class BnInterface--><g id="elem_BnInterface"><rect codeLine="12" fill="#F1F1F1" height="48" id="BnInterface" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="240" x="30" y="363"/><ellipse cx="45" cy="379" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M47.3438,374.6719 C46.4063,374.2344 45.8125,374.0938 44.9375,374.0938 C42.3125,374.0938 40.3125,376.1719 40.3125,378.8906 L40.3125,380.0156 C40.3125,382.5938 42.4219,384.4844 45.3125,384.4844 C46.5313,384.4844 47.6875,384.1875 48.4375,383.6406 C49.0156,383.2344 49.3438,382.7813 49.3438,382.3906 C49.3438,381.9375 48.9531,381.5469 48.4844,381.5469 C48.2656,381.5469 48.0625,381.625 47.875,381.8125 C47.4219,382.2969 47.4219,382.2969 47.2344,382.3906 C46.8125,382.6563 46.125,382.7813 45.3594,382.7813 C43.3125,382.7813 42.0156,381.6875 42.0156,379.9844 L42.0156,378.8906 C42.0156,377.1094 43.2656,375.7969 45,375.7969 C45.5781,375.7969 46.1875,375.9531 46.6563,376.2031 C47.1406,376.4844 47.3125,376.7031 47.4063,377.1094 C47.4688,377.5156 47.5,377.6406 47.6406,377.7656 C47.7813,377.9063 48.0156,378.0156 48.2344,378.0156 C48.5,378.0156 48.7656,377.875 48.9375,377.6563 C49.0469,377.5 49.0781,377.3125 49.0781,376.8906 L49.0781,375.4688 C49.0781,375.0313 49.0625,374.9063 48.9688,374.75 C48.8125,374.4844 48.5313,374.3438 48.2344,374.3438 C47.9375,374.3438 47.7344,374.4375 47.5156,374.75 L47.3438,374.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="85" x="59" y="383.8467">BnInterface</text><rect fill="#FFFFFF" height="15.9688" style="stroke:#181818;stroke-width:1.0;stroke-dasharray:2.0,2.0;" width="121" x="152" y="360"/><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="119" x="153" y="372.1387">IMediaPlayerService</text><line style="stroke:#181818;stroke-width:0.5;" x1="31" x2="269" y1="395" y2="395"/><line style="stroke:#181818;stroke-width:0.5;" x1="31" x2="269" y1="403" y2="403"/></g><!--class BnMediaPlayerService--><g id="elem_BnMediaPlayerService"><rect fill="#F1F1F1" height="48" id="BnMediaPlayerService" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="190" x="55" y="471"/><ellipse cx="70" cy="487" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M72.3438,482.6719 C71.4063,482.2344 70.8125,482.0938 69.9375,482.0938 C67.3125,482.0938 65.3125,484.1719 65.3125,486.8906 L65.3125,488.0156 C65.3125,490.5938 67.4219,492.4844 70.3125,492.4844 C71.5313,492.4844 72.6875,492.1875 73.4375,491.6406 C74.0156,491.2344 74.3438,490.7813 74.3438,490.3906 C74.3438,489.9375 73.9531,489.5469 73.4844,489.5469 C73.2656,489.5469 73.0625,489.625 72.875,489.8125 C72.4219,490.2969 72.4219,490.2969 72.2344,490.3906 C71.8125,490.6563 71.125,490.7813 70.3594,490.7813 C68.3125,490.7813 67.0156,489.6875 67.0156,487.9844 L67.0156,486.8906 C67.0156,485.1094 68.2656,483.7969 70,483.7969 C70.5781,483.7969 71.1875,483.9531 71.6563,484.2031 C72.1406,484.4844 72.3125,484.7031 72.4063,485.1094 C72.4688,485.5156 72.5,485.6406 72.6406,485.7656 C72.7813,485.9063 73.0156,486.0156 73.2344,486.0156 C73.5,486.0156 73.7656,485.875 73.9375,485.6563 C74.0469,485.5 74.0781,485.3125 74.0781,484.8906 L74.0781,483.4688 C74.0781,483.0313 74.0625,482.9063 73.9688,482.75 C73.8125,482.4844 73.5313,482.3438 73.2344,482.3438 C72.9375,482.3438 72.7344,482.4375 72.5156,482.75 L72.3438,482.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="158" x="84" y="491.8467">BnMediaPlayerService</text><line style="stroke:#181818;stroke-width:0.5;" x1="56" x2="244" y1="503" y2="503"/><line style="stroke:#181818;stroke-width:0.5;" x1="56" x2="244" y1="511" y2="511"/></g><!--class MediaPlayerService--><g id="elem_MediaPlayerService"><rect fill="#F1F1F1" height="48" id="MediaPlayerService" rx="2.5" ry="2.5" style="stroke:#181818;stroke-width:0.5;" width="171" x="64.5" y="579"/><ellipse cx="79.5" cy="595" fill="#ADD1B2" rx="11" ry="11" style="stroke:#181818;stroke-width:1.0;"/><path d="M81.8438,590.6719 C80.9063,590.2344 80.3125,590.0938 79.4375,590.0938 C76.8125,590.0938 74.8125,592.1719 74.8125,594.8906 L74.8125,596.0156 C74.8125,598.5938 76.9219,600.4844 79.8125,600.4844 C81.0313,600.4844 82.1875,600.1875 82.9375,599.6406 C83.5156,599.2344 83.8438,598.7813 83.8438,598.3906 C83.8438,597.9375 83.4531,597.5469 82.9844,597.5469 C82.7656,597.5469 82.5625,597.625 82.375,597.8125 C81.9219,598.2969 81.9219,598.2969 81.7344,598.3906 C81.3125,598.6563 80.625,598.7813 79.8594,598.7813 C77.8125,598.7813 76.5156,597.6875 76.5156,595.9844 L76.5156,594.8906 C76.5156,593.1094 77.7656,591.7969 79.5,591.7969 C80.0781,591.7969 80.6875,591.9531 81.1563,592.2031 C81.6406,592.4844 81.8125,592.7031 81.9063,593.1094 C81.9688,593.5156 82,593.6406 82.1406,593.7656 C82.2813,593.9063 82.5156,594.0156 82.7344,594.0156 C83,594.0156 83.2656,593.875 83.4375,593.6563 C83.5469,593.5 83.5781,593.3125 83.5781,592.8906 L83.5781,591.4688 C83.5781,591.0313 83.5625,590.9063 83.4688,590.75 C83.3125,590.4844 83.0313,590.3438 82.7344,590.3438 C82.4375,590.3438 82.2344,590.4375 82.0156,590.75 L81.8438,590.6719 Z " fill="#000000"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="139" x="93.5" y="599.8467">MediaPlayerService</text><line style="stroke:#181818;stroke-width:0.5;" x1="65.5" x2="234.5" y1="611" y2="611"/><line style="stroke:#181818;stroke-width:0.5;" x1="65.5" x2="234.5" y1="619" y2="619"/></g><!--reverse link RefBase to IInterface--><g id="link_RefBase_IInterface"><path codeLine="10" d="M166.8071,69.3185 C180.0661,86.4945 187.314,95.884 201.881,114.755 " fill="none" id="RefBase-backto-IInterface" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="155.808,55.07,162.0576,72.9849,171.5566,65.6521,155.808,55.07" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link IInterface to IMediaPlayerService--><g id="link_IInterface_IMediaPlayerService"><path codeLine="11" d="M230.8207,197.0146 C232.8897,218.0526 233.818,227.481 235.704,246.661 " fill="none" id="IInterface-backto-IMediaPlayerService" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="229.059,179.101,224.8495,197.6018,236.7919,196.4273,229.059,179.101" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link RefBase to IBinder--><g id="link_RefBase_IBinder"><path codeLine="13" d="M116.237,70.7655 C105.133,90.5435 98.0302,103.196 86.9321,122.965 " fill="none" id="RefBase-backto-IBinder" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="125.049,55.07,111.0052,67.8282,121.4689,73.7028,125.049,55.07" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link IBinder to BBinder--><g id="link_IBinder_BBinder"><path codeLine="14" d="M69.9527,189.1476 C68.0759,208.2296 67.1615,217.525 65.093,238.555 " fill="none" id="IBinder-backto-BBinder" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="71.7146,171.234,63.9815,188.5603,75.9239,189.7349,71.7146,171.234" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link BBinder to BnInterface--><g id="link_BBinder_BnInterface"><path codeLine="15" d="M97.0455,317.3995 C111.5997,336.2535 118.85,345.647 132.126,362.845 " fill="none" id="BBinder-backto-BnInterface" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="86.0464,303.151,92.2959,321.0659,101.795,313.7332,86.0464,303.151" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link IMediaPlayerService to BnInterface--><g id="link_IMediaPlayerService_BnInterface"><path codeLine="16" d="M209.1927,309.3184 C193.9247,329.0964 183.042,343.196 167.782,362.965 " fill="none" id="IMediaPlayerService-backto-BnInterface" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="220.192,295.07,204.4433,305.6519,213.9422,312.9848,220.192,295.07" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link BnInterface to BnMediaPlayerService--><g id="link_BnInterface_BnMediaPlayerService"><path codeLine="17" d="M150,429 C150,446.658 150,452.941 150,470.678 " fill="none" id="BnInterface-backto-BnMediaPlayerService" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="150,411,144,429,156,429,150,411" style="stroke:#181818;stroke-width:1.0;"/></g><!--reverse link BnMediaPlayerService to MediaPlayerService--><g id="link_BnMediaPlayerService_MediaPlayerService"><path codeLine="18" d="M150,537 C150,554.6584 150,560.9408 150,578.6784 " fill="none" id="BnMediaPlayerService-backto-MediaPlayerService" style="stroke:#181818;stroke-width:1.0;"/><polygon fill="none" points="150,519,144,537,156,537,150,519" style="stroke:#181818;stroke-width:1.0;"/></g><!--SRC=[KrVmJKt9J0p8IQnCBGfEBIhBJ4vzldlviyxzJritFz-ycoiphoIrA2qnELN1qoapBoMr25a4KozNSavYSR624qIjGZMN0X3KvUU552Nc5IScbt3LGbLuUiADWIZIJYo6Mb3B5PIQvfHOdAfWKwEhYwII2qaJH0gt0_BWIcsmgB93im9gCvI624BzmEM48fY7v1fCSp4L8R5XabWSZKqGeXnJ7000]--></g></svg>

<p>可以看到MediaPlayerService继承自BBinder，就是binder C/S架构的服务端，是媒体服务(“media.player”)的提供者。通过ServiceManager系统把MediaPlayerService注册到binder系统中。</p>
<p>MediaPlayerService类并不是我们的主角，这里介绍MediaPlayerService的目的是来熟悉一下服务和BBinder的关系。addService的服务端的主角是service_manager（定义在service_manager.c中，会面会详细介绍），但是service_manager并没有接入BBinder框架，而是通过直接打开binder设备来通信。作为binder服务的管理者，service_manager在实现上就和普通的binder服务不同。</p>
<h3 id="BpServiceManager-addService"><a href="#BpServiceManager-addService" class="headerlink" title="BpServiceManager::addService"></a>BpServiceManager::addService</h3><p>来看下BpServiceManager的addService是如何实现的：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\IServiceManager.cpp</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BpServiceManager</span> : <span class="keyword">public</span> BpInterface&lt;IServiceManager&gt;</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">explicit</span> <span class="title">BpServiceManager</span><span class="params">(<span class="type">const</span> sp&lt;IBinder&gt;&amp; impl)</span>  <span class="comment">//impl参数就是BpBinder(0)</span></span></span><br><span class="line"><span class="function">        : BpInterface&lt;IServiceManager&gt;(impl)  &#123;</span>&#125;</span><br><span class="line">    ......</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="type">status_t</span> <span class="title">addService</span><span class="params">(<span class="type">const</span> String16&amp; name, <span class="type">const</span> sp&lt;IBinder&gt;&amp; service,</span></span></span><br><span class="line"><span class="params"><span class="function">            <span class="type">bool</span> allowIsolated)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Parcel data, reply;</span><br><span class="line">        <span class="comment">//IServiceManager::getInterfaceDescriptor()返回&quot;android.os.IServiceManager&quot;</span></span><br><span class="line">        data.<span class="built_in">writeInterfaceToken</span>(IServiceManager::<span class="built_in">getInterfaceDescriptor</span>());</span><br><span class="line">        data.<span class="built_in">writeString16</span>(name);  <span class="comment">//name就是&quot;media.player&quot;</span></span><br><span class="line">        data.<span class="built_in">writeStrongBinder</span>(service);  <span class="comment">//service就是MediaPlayerService类对象</span></span><br><span class="line">        data.<span class="built_in">writeInt32</span>(allowIsolated ? <span class="number">1</span> : <span class="number">0</span>);  <span class="comment">//allowIsolated默认是false，所以此处为0</span></span><br><span class="line">        <span class="comment">//remote()返回mRemote（就是BpBinder），此处就是调用BpBinder的transact</span></span><br><span class="line">        <span class="type">status_t</span> err = <span class="built_in">remote</span>()-&gt;<span class="built_in">transact</span>(ADD_SERVICE_TRANSACTION, data, &amp;reply);</span><br><span class="line">        <span class="keyword">return</span> err == NO_ERROR ? reply.<span class="built_in">readExceptionCode</span>() : err;</span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>BpServiceManager的构造函数没有任何自定义实现，直接把参数（BpBinder）交给了父类。addService函数首先把service信息填充到Parcel中，然后调用BpBinder的transact。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\BpBinder.cpp</span></span><br><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">BpBinder::transact</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">uint32_t</span> code, <span class="type">const</span> Parcel&amp; data, Parcel* reply, <span class="type">uint32_t</span> flags)</span>  <span class="comment">//flags默认是0</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// Once a binder has died, it will never come back to life.</span></span><br><span class="line">    <span class="keyword">if</span> (mAlive) &#123;</span><br><span class="line">        <span class="type">status_t</span> status = IPCThreadState::<span class="built_in">self</span>()-&gt;<span class="built_in">transact</span>(</span><br><span class="line">            mHandle, code, data, reply, flags);</span><br><span class="line">        <span class="keyword">if</span> (status == DEAD_OBJECT) mAlive = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> status;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> DEAD_OBJECT;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>BpBinder的transact啥也没干，直接把请求交给了IPCThreadState的transact。首先看下IPCThreadState::self()的实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\IPCThreadState.cpp</span></span><br><span class="line"><span class="type">static</span> <span class="type">pthread_mutex_t</span> gTLSMutex = PTHREAD_MUTEX_INITIALIZER;</span><br><span class="line"><span class="type">static</span> <span class="type">bool</span> gHaveTLS = <span class="literal">false</span>;</span><br><span class="line"><span class="type">static</span> <span class="type">pthread_key_t</span> gTLS = <span class="number">0</span>; <span class="comment">//pthread_key_t是一个TheadLocal变量的key。</span></span><br><span class="line"></span><br><span class="line"><span class="function">IPCThreadState* <span class="title">IPCThreadState::self</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (gHaveTLS) &#123; <span class="comment">//首次调用gHavsTLS是false</span></span><br><span class="line">restart:</span><br><span class="line">        <span class="type">const</span> <span class="type">pthread_key_t</span> k = gTLS;</span><br><span class="line">        IPCThreadState* st = (IPCThreadState*)<span class="built_in">pthread_getspecific</span>(k);</span><br><span class="line">        <span class="keyword">if</span> (st) <span class="keyword">return</span> st;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> IPCThreadState;  <span class="comment">//IPCThreadState的构造函数会把自己加到ThreadLocal变量中</span></span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">    <span class="built_in">pthread_mutex_lock</span>(&amp;gTLSMutex);</span><br><span class="line">    <span class="keyword">if</span> (!gHaveTLS) &#123;</span><br><span class="line">        <span class="comment">//创建一个ThreadLocal变量，key存放到gTLS全局标量中</span></span><br><span class="line">        <span class="type">int</span> key_create_value = <span class="built_in">pthread_key_create</span>(&amp;gTLS, threadDestructor);</span><br><span class="line">        <span class="keyword">if</span> (key_create_value != <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="built_in">pthread_mutex_unlock</span>(&amp;gTLSMutex);</span><br><span class="line">            <span class="built_in">ALOGW</span>(<span class="string">&quot;IPCThreadState::self() unable to create TLS key, expect a crash: %s\n&quot;</span>, <span class="built_in">strerror</span>(key_create_value));</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        gHaveTLS = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">pthread_mutex_unlock</span>(&amp;gTLSMutex);</span><br><span class="line">    <span class="keyword">goto</span> restart;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>IPCThreadState::self()的作用就是创建了一个特定线程（TheadLocal数据）的IPCThreadState，所以每个线程维护一个IPCThreadState对象。关于native层ThreadLocal介绍可以参考 <a target="_blank" rel="noopener external nofollow noreferrer" href="https://linux.die.net/man/3/pthread_key_create">https://linux.die.net/man/3/pthread_key_create</a>。再看下IPCThreadState构造函数：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">IPCThreadState::<span class="built_in">IPCThreadState</span>()</span><br><span class="line">    : <span class="built_in">mProcess</span>(ProcessState::<span class="built_in">self</span>()),  <span class="comment">//ProcessState又出现了，ProcessState会打开binder设备</span></span><br><span class="line">      <span class="built_in">mStrictModePolicy</span>(<span class="number">0</span>),</span><br><span class="line">      <span class="built_in">mLastTransactionBinderFlags</span>(<span class="number">0</span>)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">pthread_setspecific</span>(gTLS, <span class="keyword">this</span>);  <span class="comment">//把自己放到ThreadLocal中</span></span><br><span class="line">    <span class="built_in">clearCaller</span>();</span><br><span class="line">    mIn.<span class="built_in">setDataCapacity</span>(<span class="number">256</span>);  <span class="comment">//mIn是个Parcel对象，用于存储从binder接收的数据</span></span><br><span class="line">    mOut.<span class="built_in">setDataCapacity</span>(<span class="number">256</span>); <span class="comment">//mOut也是Parcel对象，用于存储向binder发送的数据</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>IPCThreadState和ProcessState的关系就清楚了，通过mProcess变量持有了ProcessState对象的引用。</p>
<h3 id="IPCThreadState-transact"><a href="#IPCThreadState-transact" class="headerlink" title="IPCThreadState::transact()"></a>IPCThreadState::transact()</h3><p>看一下IPCThreadState::transact的实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//handle = 0，就是ServiceManager在binder系统中的标识</span></span><br><span class="line"><span class="comment">//code = ADD_SERVICE_TRANSACTION</span></span><br><span class="line"><span class="comment">//data 就是BpServiceManager.addService中组装的要通过binder发送出去的Parcel数据</span></span><br><span class="line"><span class="comment">//flags = 0</span></span><br><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">IPCThreadState::transact</span><span class="params">(<span class="type">int32_t</span> handle,</span></span></span><br><span class="line"><span class="params"><span class="function">                                  <span class="type">uint32_t</span> code, <span class="type">const</span> Parcel&amp; data,</span></span></span><br><span class="line"><span class="params"><span class="function">                                  Parcel* reply, <span class="type">uint32_t</span> flags)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">status_t</span> err = data.<span class="built_in">errorCheck</span>();</span><br><span class="line"></span><br><span class="line">    flags |= TF_ACCEPT_FDS;</span><br><span class="line">    ......</span><br><span class="line">    <span class="keyword">if</span> (err == NO_ERROR) &#123;</span><br><span class="line">        <span class="built_in">LOG_ONEWAY</span>(<span class="string">&quot;&gt;&gt;&gt;&gt; SEND from pid %d uid %d %s&quot;</span>, <span class="built_in">getpid</span>(), <span class="built_in">getuid</span>(),</span><br><span class="line">            (flags &amp; TF_ONE_WAY) == <span class="number">0</span> ? <span class="string">&quot;READ REPLY&quot;</span> : <span class="string">&quot;ONE WAY&quot;</span>);</span><br><span class="line">        err = <span class="built_in">writeTransactionData</span>(BC_TRANSACTION, flags, handle, code, data, <span class="literal">NULL</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">    <span class="keyword">if</span> ((flags &amp; TF_ONE_WAY) == <span class="number">0</span>) &#123;  <span class="comment">//flags初始值是0，走该分支</span></span><br><span class="line">        ......</span><br><span class="line">        <span class="keyword">if</span> (reply) &#123; <span class="comment">//replay不为空，走if分支</span></span><br><span class="line">            err = <span class="built_in">waitForResponse</span>(reply);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            Parcel fakeReply;</span><br><span class="line">            err = <span class="built_in">waitForResponse</span>(&amp;fakeReply);</span><br><span class="line">        &#125;</span><br><span class="line">        ......</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        err = <span class="built_in">waitForResponse</span>(<span class="literal">NULL</span>, <span class="literal">NULL</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> err;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>IPCThreadState::transact有两个重点函数调用：writeTransactionData和waitForResponse。分别看下。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">IPCThreadState::writeTransactionData</span><span class="params">(<span class="type">int32_t</span> cmd, <span class="type">uint32_t</span> binderFlags,</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">int32_t</span> handle, <span class="type">uint32_t</span> code, <span class="type">const</span> Parcel&amp; data, <span class="type">status_t</span>* statusBuffer)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    binder_transaction_data tr;</span><br><span class="line"></span><br><span class="line">    tr.target.ptr = <span class="number">0</span>; <span class="comment">/* Don&#x27;t pass uninitialized stack data to a remote process */</span></span><br><span class="line">    tr.target.handle = handle;  <span class="comment">//target表示发送给谁，此处handle为0就代表ServiceManager</span></span><br><span class="line">    tr.code = code;  <span class="comment">//code值为ADD_SERVICE_TRANSACTION，addService</span></span><br><span class="line">    tr.flags = binderFlags;</span><br><span class="line">    tr.cookie = <span class="number">0</span>;</span><br><span class="line">    tr.sender_pid = <span class="number">0</span>;</span><br><span class="line">    tr.sender_euid = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">const</span> <span class="type">status_t</span> err = data.<span class="built_in">errorCheck</span>();</span><br><span class="line">    <span class="keyword">if</span> (err == NO_ERROR) &#123;</span><br><span class="line">        tr.data_size = data.<span class="built_in">ipcDataSize</span>(); <span class="comment">//Parcel数据大小</span></span><br><span class="line">        <span class="comment">//ptr.buffer就是Parcel的mData的地址</span></span><br><span class="line">        tr.data.ptr.buffer = data.<span class="built_in">ipcData</span>();</span><br><span class="line">        tr.offsets_size = data.<span class="built_in">ipcObjectsCount</span>()*<span class="built_in">sizeof</span>(<span class="type">binder_size_t</span>);</span><br><span class="line">        <span class="comment">//ptr.offsets指向Parcel的mObjects</span></span><br><span class="line">        tr.data.ptr.offsets = data.<span class="built_in">ipcObjects</span>();</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (statusBuffer) &#123;</span><br><span class="line">        ......</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">return</span> (mLastError = err);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//只是把数据写到mOut中，并没有发送出去</span></span><br><span class="line">    <span class="comment">//需要注意下数据结构的转换：把输入的Parcel转换成binder_transaction_data</span></span><br><span class="line">    mOut.<span class="built_in">writeInt32</span>(cmd);  <span class="comment">//cmd=BC_TRANSACTION</span></span><br><span class="line">    mOut.<span class="built_in">write</span>(&amp;tr, <span class="built_in">sizeof</span>(tr));</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> NO_ERROR;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>writeTransactionData把要通过binder传输的数据写入mOut。这里需要注意下数据结构的变更，首先把原始的Parcel(data)转换成binder_transaction_data结构体，然后又写入到mOut中，而mOut也是个Parcel对象。</p>
<h3 id="Parcel等数据结构分析"><a href="#Parcel等数据结构分析" class="headerlink" title="Parcel等数据结构分析"></a>Parcel等数据结构分析</h3><p>我们有必要分析一下传输数据在这个过程中的转换过程。我们都知道，binder通信都是使用Parcel作为数据载体的，Parcel在传输基本数据类型（比如int、string）时，都直接写到成员变量mData指针指向的内存中。Parcel对象构建时，mData并没有指向任何内存，当真正写入数据时才通过memcpy来按需申请内存。mDataSize表示已经写入的数据大小，mDataPos指针指向下次要写入数据的位置。</p>
<p>再回顾一下<code>BpServiceManager::addService</code>拼装初始Parcel数据的代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//class BpServiceManager</span></span><br><span class="line"><span class="function"><span class="keyword">virtual</span> <span class="type">status_t</span> <span class="title">addService</span><span class="params">(<span class="type">const</span> String16&amp; name, <span class="type">const</span> sp&lt;IBinder&gt;&amp; service,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="type">bool</span> allowIsolated)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Parcel data, reply;</span><br><span class="line">    data.<span class="built_in">writeInterfaceToken</span>(IServiceManager::<span class="built_in">getInterfaceDescriptor</span>());</span><br><span class="line">    data.<span class="built_in">writeString16</span>(name);</span><br><span class="line">    data.<span class="built_in">writeStrongBinder</span>(service);</span><br><span class="line">    data.<span class="built_in">writeInt32</span>(allowIsolated ? <span class="number">1</span> : <span class="number">0</span>);</span><br><span class="line">    <span class="type">status_t</span> err = <span class="built_in">remote</span>()-&gt;<span class="built_in">transact</span>(ADD_SERVICE_TRANSACTION, data, &amp;reply);</span><br><span class="line">    <span class="keyword">return</span> err == NO_ERROR ? reply.<span class="built_in">readExceptionCode</span>() : err;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码执行后，Parcel中mData和mObjects两个成员变量可以用下图来表示：</p>
<!--  -->

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
 -->
<!-- Title: parcel_data Pages: 1 -->
<svg width="532pt" height="116pt"
 viewBox="0.00 0.00 531.50 116.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 112)">
<title>parcel_data</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-112 527.5,-112 527.5,4 -4,4"/>
<!-- mData -->
<g id="node1" class="node">
<title>mData</title>
<polygon fill="none" stroke="#000000" points="6,-79 6,-101 49,-101 49,-79 6,-79"/>
<text text-anchor="start" x="8.8415" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">mData</text>
</g>
<!-- data -->
<g id="node2" class="node">
<title>data</title>
<polygon fill="none" stroke="#000000" points="73,-79 73,-101 96,-101 96,-79 73,-79"/>
<text text-anchor="start" x="75.9474" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">len</text>
<polygon fill="none" stroke="#000000" points="96,-79 96,-101 281,-101 281,-79 96,-79"/>
<text text-anchor="start" x="98.7012" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">“android.os.IServiceManager”</text>
<polygon fill="none" stroke="#000000" points="281,-79 281,-101 304,-101 304,-79 281,-79"/>
<text text-anchor="start" x="283.9474" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">len</text>
<polygon fill="none" stroke="#000000" points="304,-79 304,-101 403,-101 403,-79 304,-79"/>
<text text-anchor="start" x="306.6546" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">“media.player”</text>
<polygon fill="none" stroke="#000000" points="403,-79 403,-101 511,-101 511,-79 403,-79"/>
<text text-anchor="start" x="405.6837" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">flat_binder_object</text>
<polygon fill="none" stroke="#000000" points="511,-79 511,-101 524,-101 524,-79 511,-79"/>
<text text-anchor="start" x="514" y="-85.4" font-family="Times,serif" font-size="14.00" fill="#000000">0</text>
</g>
<!-- mData&#45;&gt;data -->
<g id="edge1" class="edge">
<title>mData:p0&#45;&gt;data:p0</title>
<path fill="none" stroke="#000000" d="M49.1823,-90C53.9239,-90 58.7438,-90 62.7958,-90"/>
<polygon fill="#000000" stroke="#000000" points="63,-93.5001 73,-90 63,-86.5001 63,-93.5001"/>
</g>
<!-- mObjects -->
<g id="node3" class="node">
<title>mObjects</title>
<polygon fill="none" stroke="#000000" points="7,-7 7,-29 66,-29 66,-7 7,-7"/>
<text text-anchor="start" x="9.6739" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">mObjects</text>
</g>
<!-- mData&#45;&gt;mObjects -->
<!-- objects -->
<g id="node4" class="node">
<title>objects</title>
<polygon fill="none" stroke="#000000" points="397,-7 397,-29 410,-29 410,-7 397,-7"/>
<text text-anchor="start" x="400" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">0</text>
<polygon fill="none" stroke="#000000" points="410,-7 410,-29 423,-29 423,-7 410,-7"/>
<text text-anchor="start" x="413" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
<polygon fill="none" stroke="#000000" points="423,-7 423,-29 436,-29 436,-7 423,-7"/>
<text text-anchor="start" x="426" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
<polygon fill="none" stroke="#000000" points="436,-7 436,-29 449,-29 449,-7 436,-7"/>
<text text-anchor="start" x="439" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
</g>
<!-- mObjects&#45;&gt;objects -->
<g id="edge2" class="edge">
<title>mObjects&#45;&gt;objects</title>
<path fill="none" stroke="#000000" d="M65.8564,-18C172.3993,-18 278.9422,-18 385.4851,-18"/>
<polygon fill="#000000" stroke="#000000" points="385.7957,-21.5001 395.7957,-18 385.7957,-14.5001 385.7957,-21.5001"/>
</g>
<!-- objects&#45;&gt;data -->
<g id="edge3" class="edge">
<title>objects:n&#45;&gt;data:sw</title>
<path fill="none" stroke="#000000" d="M403,-29C403,-29 403,-54.2716 403,-68.8818"/>
<polygon fill="#000000" stroke="#000000" points="399.5001,-69 403,-79 406.5001,-69 399.5001,-69"/>
</g>
</g>
</svg>


<p>可以看到有个flat_binder_object结构体，这个结构体就是通过调用<code>Parcel::writeStrongBinder</code>写入的<code>sp&lt;IBinder&gt;</code>(本例中就是MediaPlayerService)。writeStrongBinder的实现与基本数据结构的写入是有区别的，专门用于承载IBinder对象的传输任务。来看下代码实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\Parcel.cpp</span></span><br><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">Parcel::writeStrongBinder</span><span class="params">(<span class="type">const</span> sp&lt;IBinder&gt;&amp; val)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">flatten_binder</span>(ProcessState::<span class="built_in">self</span>(), val, <span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">flatten_binder</span><span class="params">(<span class="type">const</span> sp&lt;ProcessState&gt;&amp; <span class="comment">/*proc*/</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> sp&lt;IBinder&gt;&amp; binder, Parcel* out)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    flat_binder_object obj;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (IPCThreadState::<span class="built_in">self</span>()-&gt;<span class="built_in">backgroundSchedulingDisabled</span>()) &#123;</span><br><span class="line">        <span class="comment">/* minimum priority for all nodes is nice 0 */</span></span><br><span class="line">        obj.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">/* minimum priority for all nodes is MAX_NICE(19) */</span></span><br><span class="line">        obj.flags = <span class="number">0x13</span> | FLAT_BINDER_FLAG_ACCEPTS_FDS;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (binder != <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="comment">//如果是Bn端的BBinder，则localBinder会返回对象指针；</span></span><br><span class="line">        <span class="comment">//Bp端的BpBinder没有重写localBinder，所以会返回NULL；</span></span><br><span class="line">        <span class="comment">//此处写入的是MediaPlayerService，是Bn端，所以local返回的就是MediaPlayerService对象</span></span><br><span class="line">        IBinder *local = binder-&gt;<span class="built_in">localBinder</span>();  </span><br><span class="line">        <span class="keyword">if</span> (!local) &#123;</span><br><span class="line">            <span class="comment">//BpBinder实现了remoteBinder，返回this指针</span></span><br><span class="line">            BpBinder *proxy = binder-&gt;<span class="built_in">remoteBinder</span>();</span><br><span class="line">            <span class="keyword">if</span> (proxy == <span class="literal">NULL</span>) &#123;</span><br><span class="line">                <span class="built_in">ALOGE</span>(<span class="string">&quot;null proxy&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="type">const</span> <span class="type">int32_t</span> handle = proxy ? proxy-&gt;<span class="built_in">handle</span>() : <span class="number">0</span>;</span><br><span class="line">            obj.type = BINDER_TYPE_HANDLE;</span><br><span class="line">            obj.binder = <span class="number">0</span>; <span class="comment">/* Don&#x27;t pass uninitialized stack data to a remote process */</span></span><br><span class="line">            obj.handle = handle;</span><br><span class="line">            obj.cookie = <span class="number">0</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//我们向Parcel中写入的是服务端IBinder，走else分支</span></span><br><span class="line">            <span class="comment">//只关重要的3句赋值代码，后面会介绍哪里会用</span></span><br><span class="line">            obj.type = BINDER_TYPE_BINDER;</span><br><span class="line">            obj.binder = <span class="built_in">reinterpret_cast</span>&lt;<span class="type">uintptr_t</span>&gt;(local-&gt;<span class="built_in">getWeakRefs</span>());</span><br><span class="line">            obj.cookie = <span class="built_in">reinterpret_cast</span>&lt;<span class="type">uintptr_t</span>&gt;(local);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        obj.type = BINDER_TYPE_BINDER;</span><br><span class="line">        obj.binder = <span class="number">0</span>;</span><br><span class="line">        obj.cookie = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">finish_flatten_binder</span>(binder, obj, out);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>flatten_binder函数把IBinder封装成flat_binder_object结构体，然后调用<code>finish_flatten_binder</code>。先看下flat_binder_object结构体的定义：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//flat_binder_object结构体定义比较简单，不多介绍。</span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">flat_binder_object</span> &#123;</span><br><span class="line">  __u32 type;  <span class="comment">//在add MediaPlayerService时type=BINDER_TYPE_BINDER</span></span><br><span class="line">  __u32 flags;</span><br><span class="line">  <span class="keyword">union</span> &#123;</span><br><span class="line">    <span class="type">binder_uintptr_t</span> binder;</span><br><span class="line">    __u32 handle;</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="type">binder_uintptr_t</span> cookie;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>进入<code>finish_flatten_binder</code>函数看下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\libs\binder\Parcel.cpp</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//可以看出传入的binder参数没有用到，所以flat_binder_object就是用于传输的数据结构。</span></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">static</span> <span class="type">status_t</span> <span class="title">finish_flatten_binder</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> sp&lt;IBinder&gt;&amp; <span class="comment">/*binder*/</span>, <span class="type">const</span> flat_binder_object&amp; flat, Parcel* out)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> out-&gt;<span class="built_in">writeObject</span>(flat, <span class="literal">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">Parcel::writeObject</span><span class="params">(<span class="type">const</span> flat_binder_object&amp; val, <span class="type">bool</span> nullMetaData)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">const</span> <span class="type">bool</span> enoughData = (mDataPos+<span class="built_in">sizeof</span>(val)) &lt;= mDataCapacity;</span><br><span class="line">    <span class="type">const</span> <span class="type">bool</span> enoughObjects = mObjectsSize &lt; mObjectsCapacity;</span><br><span class="line">    <span class="keyword">if</span> (enoughData &amp;&amp; enoughObjects) &#123;</span><br><span class="line">restart_write: <span class="comment">//注意这个goto跳转标记，在Parcel内存不足以保存要写入的数据时，会先去申请内存，然后再跳转回来</span></span><br><span class="line">        <span class="comment">//把刚才的flat_binder_object数据结构保存到mData所指向内存的mDataPos位置</span></span><br><span class="line">        *<span class="built_in">reinterpret_cast</span>&lt;flat_binder_object*&gt;(mData+mDataPos) = val;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// remember if it&#x27;s a file descriptor</span></span><br><span class="line">        <span class="keyword">if</span> (val.type == BINDER_TYPE_FD) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!mAllowFds) &#123;</span><br><span class="line">                <span class="comment">// fail before modifying our object index</span></span><br><span class="line">                <span class="keyword">return</span> FDS_NOT_ALLOWED;</span><br><span class="line">            &#125;</span><br><span class="line">            mHasFds = mFdsKnown = <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Need to write meta-data?</span></span><br><span class="line">        <span class="keyword">if</span> (nullMetaData || val.binder != <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">//除了把数据写到mData，还会在mObjects中再记录一下数据的偏移地址mDataPos</span></span><br><span class="line">            mObjects[mObjectsSize] = mDataPos;</span><br><span class="line">            <span class="comment">//也是非常重要的一句代码，会调用cookie-&gt;incStrong，这样对象就不会被释放了</span></span><br><span class="line">            <span class="built_in">acquire_object</span>(ProcessState::<span class="built_in">self</span>(), val, <span class="keyword">this</span>, &amp;mOpenAshmemSize);</span><br><span class="line">            mObjectsSize++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//完成写入操作，把mDataPos指向新的可写位置，并更新数据大小mDataSize</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">finishWrite</span>(<span class="built_in">sizeof</span>(flat_binder_object));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//下面的代码是在内存不足以存放要写入的数据时来增加内存的</span></span><br><span class="line">    <span class="keyword">if</span> (!enoughData) &#123;</span><br><span class="line">        <span class="type">const</span> <span class="type">status_t</span> err = <span class="built_in">growData</span>(<span class="built_in">sizeof</span>(val));</span><br><span class="line">        <span class="keyword">if</span> (err != NO_ERROR) <span class="keyword">return</span> err;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!enoughObjects) &#123;</span><br><span class="line">        <span class="type">size_t</span> newSize = ((mObjectsSize+<span class="number">2</span>)*<span class="number">3</span>)/<span class="number">2</span>;</span><br><span class="line">        <span class="keyword">if</span> (newSize*<span class="built_in">sizeof</span>(<span class="type">binder_size_t</span>) &lt; mObjectsSize) <span class="keyword">return</span> NO_MEMORY;   <span class="comment">// overflow</span></span><br><span class="line">        <span class="type">binder_size_t</span>* objects = (<span class="type">binder_size_t</span>*)<span class="built_in">realloc</span>(mObjects, newSize*<span class="built_in">sizeof</span>(<span class="type">binder_size_t</span>));</span><br><span class="line">        <span class="keyword">if</span> (objects == <span class="literal">NULL</span>) <span class="keyword">return</span> NO_MEMORY;</span><br><span class="line">        mObjects = objects;</span><br><span class="line">        mObjectsCapacity = newSize;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">goto</span> restart_write;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>至此，Parcel数据结构的拼装就分析完了。但是作为binder传输的数据载体，Parcel的任务还没有结束。继续沿着传输链条向后分析。先来回忆一下数据传输链条：</p>
<ol>
<li><code>BpServiceManager::addService</code>中拼装完Parcel数据结构后，就调用了<code>remote()-&gt;transact</code>，<code>remote()</code>函数返回的就是BpBinder；</li>
<li>BpBinder::transact接收到Parcel后，原封不动的传给了<code>IPCThreadState::self()-&gt;transact</code>;</li>
<li><code>IPCThreadState::self()-&gt;transact</code>会调用<code>IPCThreadState::writeTransactionData</code>把原Parcel数据写入变量名为mOut的Parcel对象中。</li>
</ol>
<p>现在我们再把<code>IPCThreadState::writeTransactionData</code>函数贴出来看下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">IPCThreadState::writeTransactionData</span><span class="params">(<span class="type">int32_t</span> cmd, <span class="type">uint32_t</span> binderFlags,</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">int32_t</span> handle, <span class="type">uint32_t</span> code, <span class="type">const</span> Parcel&amp; data, <span class="type">status_t</span>* statusBuffer)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    binder_transaction_data tr;</span><br><span class="line"></span><br><span class="line">    tr.target.ptr = <span class="number">0</span>; <span class="comment">/* Don&#x27;t pass uninitialized stack data to a remote process */</span></span><br><span class="line">    tr.target.handle = handle;  <span class="comment">//target表示发送给谁，handle为0就代表ServiceManager</span></span><br><span class="line">    tr.code = code;  <span class="comment">//code值为ADD_SERVICE_TRANSACTION，就是我们分析的addService</span></span><br><span class="line">    tr.flags = binderFlags;</span><br><span class="line">    tr.cookie = <span class="number">0</span>;</span><br><span class="line">    tr.sender_pid = <span class="number">0</span>;</span><br><span class="line">    tr.sender_euid = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">const</span> <span class="type">status_t</span> err = data.<span class="built_in">errorCheck</span>();</span><br><span class="line">    <span class="keyword">if</span> (err == NO_ERROR) &#123;</span><br><span class="line">        tr.data_size = data.<span class="built_in">ipcDataSize</span>(); <span class="comment">//Parcel数据大小</span></span><br><span class="line">        <span class="comment">//ptr.buffer就是Parcel的mData的地址，addService瓶装的Parcel数据都放在以mData为首地址的内存中</span></span><br><span class="line">        tr.data.ptr.buffer = data.<span class="built_in">ipcData</span>();  <span class="comment">//指向Parcel.mData</span></span><br><span class="line">        tr.offsets_size = data.<span class="built_in">ipcObjectsCount</span>()*<span class="built_in">sizeof</span>(<span class="type">binder_size_t</span>);</span><br><span class="line">        <span class="comment">//ptr.offsets会指向Parcel的mObjects数组的首地址，数组中存放着flat_binder_object结构体在mData中的偏移</span></span><br><span class="line">        tr.data.ptr.offsets = data.<span class="built_in">ipcObjects</span>();</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (statusBuffer) &#123;</span><br><span class="line">        ......</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">return</span> (mLastError = err);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//只是把数据写到mOut中，并没有发送出去</span></span><br><span class="line">    <span class="comment">//需要注意下数据结构的转换：把输入的Parcel转换成binder_transaction_data.</span></span><br><span class="line">    <span class="comment">//在IPCThreadState构造函数中mOut设置存储大小是256，binder_transaction_data的大小肯定不会大于256</span></span><br><span class="line">    mOut.<span class="built_in">writeInt32</span>(cmd);  <span class="comment">//cmd=BC_TRANSACTION</span></span><br><span class="line">    mOut.<span class="built_in">write</span>(&amp;tr, <span class="built_in">sizeof</span>(tr));</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> NO_ERROR;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>传输数据已经写入到mOut表示Parcel类中，我们看下此时的mOut数据：</p>
<!--  -->
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
 -->
<!-- Title: parcel_data Pages: 1 -->
<svg width="268pt" height="44pt"
 viewBox="0.00 0.00 268.00 44.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 40)">
<title>parcel_data</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-40 264,-40 264,4 -4,4"/>
<!-- mData -->
<g id="node1" class="node">
<title>mData</title>
<polygon fill="none" stroke="#000000" points="6,-7 6,-29 49,-29 49,-7 6,-7"/>
<text text-anchor="start" x="8.8415" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">mData</text>
</g>
<!-- data -->
<g id="node2" class="node">
<title>data</title>
<polygon fill="none" stroke="#000000" points="90,-7 90,-29 120,-29 120,-7 90,-7"/>
<text text-anchor="start" x="92.9474" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">cmd</text>
<polygon fill="none" stroke="#000000" points="120,-7 120,-29 260,-29 260,-7 120,-7"/>
<text text-anchor="start" x="122.7468" y="-13.4" font-family="Times,serif" font-size="14.00" fill="#000000">binder_transaction_data</text>
</g>
<!-- mData&#45;&gt;data -->
<g id="edge1" class="edge">
<title>mData:0&#45;&gt;data:0</title>
<path fill="none" stroke="#000000" d="M49.2343,-18C58.3067,-18 69.251,-18 79.9224,-18"/>
<polygon fill="#000000" stroke="#000000" points="80,-21.5001 90,-18 80,-14.5001 80,-21.5001"/>
</g>
</g>
</svg>


<p>来看下<code>binder_transaction_data</code>结构体的定义：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//binder.h</span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">binder_transaction_data</span> &#123;</span><br><span class="line">  <span class="keyword">union</span> &#123;</span><br><span class="line">    __u32 handle; <span class="comment">//handle为0就代表ServiceManager</span></span><br><span class="line">    <span class="type">binder_uintptr_t</span> ptr;</span><br><span class="line">  &#125; target;  <span class="comment">//target表示数据传输的目标</span></span><br><span class="line">  <span class="type">binder_uintptr_t</span> cookie;  <span class="comment">//addService流程设置该值为无效值0</span></span><br><span class="line">  __u32 code;  <span class="comment">//code值为ADD_SERVICE_TRANSACTION，就是我们分析的addService</span></span><br><span class="line">  __u32 flags;</span><br><span class="line">  <span class="type">pid_t</span> sender_pid;</span><br><span class="line">  <span class="type">uid_t</span> sender_euid;</span><br><span class="line">  <span class="type">binder_size_t</span> data_size;  <span class="comment">//Parcel的mData的有效数据大小</span></span><br><span class="line">  <span class="type">binder_size_t</span> offsets_size;</span><br><span class="line">  <span class="keyword">union</span> &#123;</span><br><span class="line">    <span class="keyword">struct</span> &#123;</span><br><span class="line">      <span class="comment">//buffer指向Parcel的mData所指向的内存地址，注意这里只是内存首地址，</span></span><br><span class="line">      <span class="comment">//并没有进行内存拷贝，当binder驱动收到数据后再通过copy_from_user</span></span><br><span class="line">      <span class="comment">//把用户态的内存拷贝到内核态。这样就减少了一次内存的拷贝，因为即使先拷贝了一次，</span></span><br><span class="line">      <span class="comment">//在驱动中依然要通过copy_from_user进行一次拷贝。</span></span><br><span class="line">      <span class="type">binder_uintptr_t</span> buffer;  </span><br><span class="line">      <span class="type">binder_uintptr_t</span> offsets; <span class="comment">//指向Parcel的mObjects</span></span><br><span class="line">    &#125; ptr;</span><br><span class="line">    __u8 buf[<span class="number">8</span>];</span><br><span class="line">  &#125; data;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="IPCThreadState-waitForResponse"><a href="#IPCThreadState-waitForResponse" class="headerlink" title="IPCThreadState::waitForResponse"></a>IPCThreadState::waitForResponse</h3><p>现在要发送的数据已经写到IPCThreadState::mOut中了，怎么发送出去的呢？</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">IPCThreadState::waitForResponse</span><span class="params">(Parcel *reply, <span class="type">status_t</span> *acquireResult)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">uint32_t</span> cmd;</span><br><span class="line">    <span class="type">int32_t</span> err;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> ((err=<span class="built_in">talkWithDriver</span>()) &lt; NO_ERROR) <span class="keyword">break</span>; <span class="comment">//talkWithDriver需要重点分析</span></span><br><span class="line">        err = mIn.<span class="built_in">errorCheck</span>();</span><br><span class="line">        <span class="keyword">if</span> (err &lt; NO_ERROR) <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">if</span> (mIn.<span class="built_in">dataAvail</span>() == <span class="number">0</span>) <span class="keyword">continue</span>;</span><br><span class="line"></span><br><span class="line">        cmd = (<span class="type">uint32_t</span>)mIn.<span class="built_in">readInt32</span>();</span><br><span class="line"></span><br><span class="line">        ......</span><br><span class="line"></span><br><span class="line">        <span class="keyword">switch</span> (cmd) &#123;</span><br><span class="line">        <span class="keyword">case</span> BR_TRANSACTION_COMPLETE:  <span class="comment">//addService成功会收到BR_TRANSACTION_COMPLETE</span></span><br><span class="line">            <span class="keyword">if</span> (!reply &amp;&amp; !acquireResult) <span class="keyword">goto</span> finish;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        ......</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">finish:</span><br><span class="line">    <span class="keyword">if</span> (err != NO_ERROR) &#123;</span><br><span class="line">        <span class="keyword">if</span> (acquireResult) *acquireResult = err;</span><br><span class="line">        <span class="keyword">if</span> (reply) reply-&gt;<span class="built_in">setError</span>(err);</span><br><span class="line">        mLastError = err;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> err;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="IPCThreadState-talkWithDriver"><a href="#IPCThreadState-talkWithDriver" class="headerlink" title="IPCThreadState::talkWithDriver"></a>IPCThreadState::talkWithDriver</h3><p>无比关键的talkWithDriver</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">status_t</span> <span class="title">IPCThreadState::talkWithDriver</span><span class="params">(<span class="type">bool</span> doReceive)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    ......</span><br><span class="line">    binder_write_read bwr;  <span class="comment">//又把数据封装成binder_write_read</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Is the read buffer empty?</span></span><br><span class="line">    <span class="type">const</span> <span class="type">bool</span> needRead = mIn.<span class="built_in">dataPosition</span>() &gt;= mIn.<span class="built_in">dataSize</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// We don&#x27;t want to write anything if we are still reading</span></span><br><span class="line">    <span class="comment">// from data left in the input buffer and the caller</span></span><br><span class="line">    <span class="comment">// has requested to read the next data.</span></span><br><span class="line">    <span class="type">const</span> <span class="type">size_t</span> outAvail = (!doReceive || needRead) ? mOut.<span class="built_in">dataSize</span>() : <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    bwr.write_size = outAvail;</span><br><span class="line">    bwr.write_buffer = (<span class="type">uintptr_t</span>)mOut.<span class="built_in">data</span>();  <span class="comment">//mOut是一个Parcel，write_buffer指向mOut.mData所指向的内存地址</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// This is what we&#x27;ll read.</span></span><br><span class="line">    <span class="keyword">if</span> (doReceive &amp;&amp; needRead) &#123;</span><br><span class="line">        <span class="comment">//mIn在IPCThreadState构造函数中设置内存大小是256</span></span><br><span class="line">        bwr.read_size = mIn.<span class="built_in">dataCapacity</span>();</span><br><span class="line">        bwr.read_buffer = (<span class="type">uintptr_t</span>)mIn.<span class="built_in">data</span>();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        bwr.read_size = <span class="number">0</span>;</span><br><span class="line">        bwr.read_buffer = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ......</span><br><span class="line"></span><br><span class="line">    bwr.write_consumed = <span class="number">0</span>;</span><br><span class="line">    bwr.read_consumed = <span class="number">0</span>;</span><br><span class="line">    <span class="type">status_t</span> err;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        <span class="comment">//通过系统调用ioctl把addService的请求发送给binder驱动</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">ioctl</span>(mProcess-&gt;mDriverFD, BINDER_WRITE_READ, &amp;bwr) &gt;= <span class="number">0</span>)</span><br><span class="line">            err = NO_ERROR;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            err = -errno;</span><br><span class="line">        <span class="keyword">if</span> (mProcess-&gt;mDriverFD &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">            err = -EBADF;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">while</span> (err == -EINTR);</span><br><span class="line">    ......</span><br><span class="line">    <span class="keyword">if</span> (err &gt;= NO_ERROR) &#123;</span><br><span class="line">        <span class="keyword">if</span> (bwr.write_consumed &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (bwr.write_consumed &lt; mOut.<span class="built_in">dataSize</span>())</span><br><span class="line">                mOut.<span class="built_in">remove</span>(<span class="number">0</span>, bwr.write_consumed);</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                mOut.<span class="built_in">setDataSize</span>(<span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (bwr.read_consumed &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            mIn.<span class="built_in">setDataSize</span>(bwr.read_consumed);</span><br><span class="line">            mIn.<span class="built_in">setDataPosition</span>(<span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        ......</span><br><span class="line">        <span class="keyword">return</span> NO_ERROR;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> err;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>addService的客户端的流程就分析到这里。关于binder驱动里面的处理可以分析内核源码，从binder.c的<code>binder_ioctl</code>函数开始分析。<code>binder_ioctl</code>就是系统调用<code>ioctl</code>的执行函数。后续会持续补充…</p>
<h2 id="4-ServiceManager分析"><a href="#4-ServiceManager分析" class="headerlink" title="4. ServiceManager分析"></a>4. ServiceManager分析</h2><h3 id="入口函数-main"><a href="#入口函数-main" class="headerlink" title="入口函数 main"></a>入口函数 main</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//frameworks\native\cmds\servicemanager\service_manager.c</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span>** argv)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">binder_state</span> *bs;</span><br><span class="line">    <span class="keyword">union</span> <span class="title class_">selinux_callback</span> cb;</span><br><span class="line">    <span class="type">char</span> *driver;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (argc &gt; <span class="number">1</span>) &#123;</span><br><span class="line">        driver = argv[<span class="number">1</span>];</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        driver = <span class="string">&quot;/dev/binder&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    bs = <span class="built_in">binder_open</span>(driver, <span class="number">128</span>*<span class="number">1024</span>);  <span class="comment">//打开binder设备</span></span><br><span class="line">    ......</span><br><span class="line">    <span class="comment">//把自己设置为context_manager(ServiceManager的服务端)</span></span><br><span class="line">    <span class="comment">//该函数的目的就是通过ioctl把设置handle值为0</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">binder_become_context_manager</span>(bs)) &#123;  </span><br><span class="line">        <span class="built_in">ALOGE</span>(<span class="string">&quot;cannot become context manager (%s)\n&quot;</span>, <span class="built_in">strerror</span>(errno));</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//selinux相关的一些操作，此处省略，读者有兴趣可以自行分析</span></span><br><span class="line">    ......</span><br><span class="line"></span><br><span class="line">    <span class="built_in">binder_loop</span>(bs, svcmgr_handler);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>service_manager的main函数主要有3个重要步骤：</p>
<ol>
<li>binder_open打开binder设备；</li>
<li>成为context_manager，也就是ServiceManager；</li>
<li>进入binder_loop；</li>
</ol>
<p>我们一步步进行分析</p>
<h3 id="ServiceManager打开binder设备"><a href="#ServiceManager打开binder设备" class="headerlink" title="ServiceManager打开binder设备"></a>ServiceManager打开binder设备</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">binder_state</span> *<span class="built_in">binder_open</span>(<span class="type">const</span> <span class="type">char</span>* driver, <span class="type">size_t</span> mapsize)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">binder_state</span> *bs;</span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">binder_version</span> vers;</span><br><span class="line"></span><br><span class="line">    bs = <span class="built_in">malloc</span>(<span class="built_in">sizeof</span>(*bs));</span><br><span class="line">    <span class="keyword">if</span> (!bs) &#123;</span><br><span class="line">        errno = ENOMEM;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    bs-&gt;fd = <span class="built_in">open</span>(driver, O_RDWR | O_CLOEXEC); <span class="comment">//打开binder设备，就是&quot;/dev/binder&quot;</span></span><br><span class="line">    <span class="keyword">if</span> (bs-&gt;fd &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(stderr,<span class="string">&quot;binder: cannot open %s (%s)\n&quot;</span>,</span><br><span class="line">                driver, <span class="built_in">strerror</span>(errno));</span><br><span class="line">        <span class="keyword">goto</span> fail_open;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取驱动版本号，并对比应用和驱动的版本号是否相同</span></span><br><span class="line">    <span class="keyword">if</span> ((<span class="built_in">ioctl</span>(bs-&gt;fd, BINDER_VERSION, &amp;vers) == <span class="number">-1</span>) ||</span><br><span class="line">        (vers.protocol_version != BINDER_CURRENT_PROTOCOL_VERSION)) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(stderr,</span><br><span class="line">                <span class="string">&quot;binder: kernel driver version (%d) differs from user space version (%d)\n&quot;</span>,</span><br><span class="line">                vers.protocol_version, BINDER_CURRENT_PROTOCOL_VERSION);</span><br><span class="line">        <span class="keyword">goto</span> fail_open;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    bs-&gt;mapsize = mapsize;</span><br><span class="line">    bs-&gt;mapped = <span class="built_in">mmap</span>(<span class="literal">NULL</span>, mapsize, PROT_READ, MAP_PRIVATE, bs-&gt;fd, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (bs-&gt;mapped == MAP_FAILED) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(stderr,<span class="string">&quot;binder: cannot map device (%s)\n&quot;</span>,</span><br><span class="line">                <span class="built_in">strerror</span>(errno));</span><br><span class="line">        <span class="keyword">goto</span> fail_map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> bs;</span><br><span class="line"></span><br><span class="line">fail_map:</span><br><span class="line">    <span class="built_in">close</span>(bs-&gt;fd);</span><br><span class="line">fail_open:</span><br><span class="line">    <span class="built_in">free</span>(bs);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="成为context-manager"><a href="#成为context-manager" class="headerlink" title="成为context_manager"></a>成为context_manager</h3><p>其实就是ServiceManager。通过系统调用ioctl的BINDER_SET_CONTEXT_MGR命令来设置。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">binder_become_context_manager</span><span class="params">(<span class="keyword">struct</span> binder_state *bs)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">ioctl</span>(bs-&gt;fd, BINDER_SET_CONTEXT_MGR, <span class="number">0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>binder驱动中的处理：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//linux-4.9.243\drivers\android\binder.c</span></span><br><span class="line"><span class="type">static</span> <span class="keyword">struct</span> <span class="title class_">binder_node</span> *binder_context_mgr_node;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">static</span> <span class="type">long</span> <span class="title">binder_ioctl</span><span class="params">(<span class="keyword">struct</span> file *filp, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">switch</span> (cmd) &#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">case</span> BINDER_SET_CONTEXT_MGR:</span><br><span class="line">        ...</span><br><span class="line">        ret = <span class="built_in">binder_ioctl_set_ctx_mgr</span>(filp);</span><br><span class="line">        <span class="keyword">if</span> (ret)</span><br><span class="line">            <span class="keyword">goto</span> err;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">static</span> <span class="type">int</span> <span class="title">binder_ioctl_set_ctx_mgr</span><span class="params">(<span class="keyword">struct</span> file *filp)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">binder_proc</span> *proc = filp-&gt;private_data;</span><br><span class="line">    <span class="type">kuid_t</span> curr_euid = <span class="built_in">current_euid</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (binder_context_mgr_node != <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="built_in">pr_err</span>(<span class="string">&quot;BINDER_SET_CONTEXT_MGR already set\n&quot;</span>);</span><br><span class="line">        ret = -EBUSY;</span><br><span class="line">        <span class="keyword">goto</span> out;</span><br><span class="line">    &#125;</span><br><span class="line">    ret = <span class="built_in">security_binder_set_context_mgr</span>(proc-&gt;tsk);</span><br><span class="line">    <span class="keyword">if</span> (ret &lt; <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">goto</span> out;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">uid_valid</span>(binder_context_mgr_uid)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!<span class="built_in">uid_eq</span>(binder_context_mgr_uid, curr_euid)) &#123;</span><br><span class="line">            <span class="built_in">pr_err</span>(<span class="string">&quot;BINDER_SET_CONTEXT_MGR bad uid %d != %d\n&quot;</span>,</span><br><span class="line">                   <span class="built_in">from_kuid</span>(&amp;init_user_ns, curr_euid),</span><br><span class="line">                   <span class="built_in">from_kuid</span>(&amp;init_user_ns,</span><br><span class="line">                    binder_context_mgr_uid));</span><br><span class="line">            ret = -EPERM;</span><br><span class="line">            <span class="keyword">goto</span> out;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        binder_context_mgr_uid = curr_euid;</span><br><span class="line">    &#125;</span><br><span class="line">    binder_context_mgr_node = <span class="built_in">binder_new_node</span>(proc, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (binder_context_mgr_node == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        ret = -ENOMEM;</span><br><span class="line">        <span class="keyword">goto</span> out;</span><br><span class="line">    &#125;</span><br><span class="line">    binder_context_mgr_node-&gt;local_weak_refs++;</span><br><span class="line">    binder_context_mgr_node-&gt;local_strong_refs++;</span><br><span class="line">    binder_context_mgr_node-&gt;has_strong_ref = <span class="number">1</span>;</span><br><span class="line">    binder_context_mgr_node-&gt;has_weak_ref = <span class="number">1</span>;</span><br><span class="line">out:</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>成为context_manager就是把ServiceManager进程的信息保存到了binder驱动的binder_context_mgr_node结构体中。想要更深入分析需要了解内核编程，这里暂时就不详细分析了。</p>
<h3 id="binder-loop循环"><a href="#binder-loop循环" class="headerlink" title="binder_loop循环"></a>binder_loop循环</h3><p>然后就进入了<code>binder_loop</code>,该函数的第二个参数非常重要，接收到消息后都是在改函数中进行处理的。先看下<code>binder_loop</code>函数的实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">binder_loop</span><span class="params">(<span class="keyword">struct</span> binder_state *bs, binder_handler func)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> res;</span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">binder_write_read</span> bwr;</span><br><span class="line">    <span class="type">uint32_t</span> readbuf[<span class="number">32</span>];</span><br><span class="line"></span><br><span class="line">    bwr.write_size = <span class="number">0</span>;</span><br><span class="line">    bwr.write_consumed = <span class="number">0</span>;</span><br><span class="line">    bwr.write_buffer = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//binder主线程？</span></span><br><span class="line">    readbuf[<span class="number">0</span>] = BC_ENTER_LOOPER;</span><br><span class="line">    <span class="built_in">binder_write</span>(bs, readbuf, <span class="built_in">sizeof</span>(<span class="type">uint32_t</span>));</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        bwr.read_size = <span class="built_in">sizeof</span>(readbuf);</span><br><span class="line">        bwr.read_consumed = <span class="number">0</span>;</span><br><span class="line">        bwr.read_buffer = (<span class="type">uintptr_t</span>) readbuf;</span><br><span class="line"></span><br><span class="line">        res = <span class="built_in">ioctl</span>(bs-&gt;fd, BINDER_WRITE_READ, &amp;bwr);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (res &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="built_in">ALOGE</span>(<span class="string">&quot;binder_loop: ioctl failed (%s)\n&quot;</span>, <span class="built_in">strerror</span>(errno));</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        res = <span class="built_in">binder_parse</span>(bs, <span class="number">0</span>, (<span class="type">uintptr_t</span>) readbuf, bwr.read_consumed, func);</span><br><span class="line">        <span class="keyword">if</span> (res == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="built_in">ALOGE</span>(<span class="string">&quot;binder_loop: unexpected reply?!\n&quot;</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (res &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="built_in">ALOGE</span>(<span class="string">&quot;binder_loop: io error %d %s\n&quot;</span>, res, <span class="built_in">strerror</span>(errno));</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Android/" rel="tag"># Android</a>
              <a href="/tags/binder/" rel="tag"># binder</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/31280.html" rel="prev" title="Android Java虚拟机创建过程">
                  <i class="fa fa-angle-left"></i> Android Java虚拟机创建过程
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/27579.html" rel="next" title="Hexo User Manual">
                  Hexo User Manual <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Jason</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener external nofollow noreferrer" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener external nofollow noreferrer" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.24/fancybox/fancybox.umd.js" integrity="sha256-oyhjPiYRWGXaAt+ny/mTMWOnN1GBoZDUQnzzgC7FRI4=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>


  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":{"light":"default","dark":"dark"},"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.5.0/mermaid.min.js","integrity":"sha256-K7oJiQlDulzl24ZUFOywuYme1JqBBvQzK6m8qHjt9Gk="}}</script>
  <script type="module" src="/js/zenuml-definition-074a43fa.js"></script>
  <script type="module" src="/js/mermaid-zenuml.esm.min.mjs"></script>
  <script src="/js/third-party/tags/mermaid.js"></script>


  <script src="/js/third-party/fancybox.js"></script>



  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
